Home  >  Q&A  >  body text

Simple SQL query: sum the values ​​of the same column in one go

I have created this query:

SELECT table1.id, b.sum 
FROM table1 
CROSS JOIN (SELECT SUM(id) sum 
            FROM table1) b 
ORDER BY id DESC;

But this will produce the following results:

id sum
3 6
2 6
1 6

Sum value is printed only once. can you help me solve it.

But I want this result:

id sum
3 6
2
1

P粉685757239P粉685757239380 days ago573

reply all(1)I'll reply

  • P粉665427988

    P粉6654279882023-09-15 13:01:31

    This should do the trick:

    select 
       id,
       CASE WHEN id=(max(id) over()) 
            THEN sum(id) over (order by id) END as 'sum' 
    from cte1
    order by id desc;

    For more information, please see: Window function concepts and syntax

    reply
    0
  • Cancelreply