Home  >  Q&A  >  body text

Control the order of adjacent columns when selecting SUM

When you select via SUM, the data returned is grouped into individual records, which is nice. The query below returns the sum correctly, but the values ​​for adjacent columns always seem to be from the oldest record. Is there any way to control the order of adjacent columns? For example, return the sum and return the data for the latest row.

SELECT user_id, sale_date, SUM(totals) as total_sum WHERE user_id = 1

The following seems to have no effect. My guess is because the order is already determined and only 1 row is returned.

SELECT user_id, sale_date, SUM(totals) as total_sum WHERE user_id = 1 ORDER BY sale_date DESC

P粉187677012P粉187677012178 days ago409

reply all(1)I'll reply

  • P粉002023326

    P粉0020233262024-04-05 09:44:53

    You are right, you only get one row, but you can always do this

    Looks cleaner too

    SELECT user_id, MAX(sale_date) as LAST_Sales_date, SUM(totals) as total_sum 
    FROM table1 WHERE user_id = 1

    reply
    0
  • Cancelreply