不同/多行中的MySQL多列Sum()

时间:2019-07-29 19:53:35

标签: mysql

我的基本表格如下:

enter image description here

当我使用查询时:

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

我得到:

enter image description here

那是正确的!

要获取的正确查询是什么(每个和在不同行中):

enter image description here

我已经尝试过GROUP BY ID,CR,DRGROUP BY CR,DR,ID,但没有获得想要的结果。 (我不在乎0值是否也为NULL)

1 个答案:

答案 0 :(得分:1)

您可以这样做:

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