mysql中group by展示无值,MySQL GROUP BY列并在不同列中显示值

I have a table as below. It is required for each distinct value of ID2, and Time to select rows that have ID3 in (0,1,2,3,4). Then, I want to show 'Val' in 5 columns, and fill the empty columns with zero.

(If ID3=0 then col0=Val

If ID3=1 then col1=Val, and ...)

ID1 ID2 ID3 Val Time

1 224 0 224 10

2 224 1 48 10

3 224 4 270 15

4 224 5 1000 27

5 225 0 231 10

6 225 1 400 10

7 225 0 100 20

In other words, the output should be as follow (group by ID2, Time ):

ID2 Time col0 col1 col2 col3 col4

224 10 224 48 0 0 0

224 15 0 0 0 0 270

225 10 231 400 0 0 0

225 20 100 0 0 0 0

Note: table has 50M rows.

解决方案select id2, time,

sum(case when id3 = 0 then val else 0 end) as col0,

sum(case when id3 = 1 then val else 0 end) as col1,

sum(case when id3 = 2 then val else 0 end) as col2,

sum(case when id3 = 3 then val else 0 end) as col3,

sum(case when id3 = 4 then val else 0 end) as col4

from your_table

group by id2, time

having sum(val) > 0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值