Simple SQL query: sum the values ​​of the same column in one go
P粉685757239
P粉685757239 2023-09-14 16:21:56
0
1
572

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粉685757239
P粉685757239

reply all(1)
P粉665427988

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!