简体   繁体   中英

MySQL Multiple Columns Sum() in different / multiple rows

I have basic table looking like:

在此处输入图片说明

When I am using the Query:

SELECT *, SUM(cr) AS cr, SUM(dr) AS dr FROM my_table GROUP BY id

I am getting:

在此处输入图片说明

and that's correct!

What's the proper query to get (each sum in different row):

在此处输入图片说明

I already tried GROUP BY ID,CR,DR and GROUP BY CR,DR,ID but with not the results that I wanted. (I don't care if the 0 values are also NULL)

You can do:

select id, sum(dr) as dr, 0 as cr from my_table group by id
union all
select id, 0, sum(cr) from my_table group by id
order by id, dr desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM