表是这样的:
id | uid | type | num |
---|---|---|---|
1 | 1 | 0 | 24 |
2 | 2 | 2 | 21 |
3 | 3 | 1 | 14 |
4 | 1 | 0 | 24 |
5 | 2 | 2 | 21 |
6 | 3 | 1 | 14 |
按 uid 分组,然后根据 type 类型对 num 进行汇总,type 是固定的,一共有三种,这种应该怎么写呢?
结果大概这样: [ { uid: 1, type_0_sum: 10, type_1_sum: 12, type_2_sum: 12 }, { uid: 2, type_0_sum: 10, type_1_sum: 12, type_2_sum: 12 }, { uid: 3, type_0_sum: 10, type_1_sum: 12, type_2_sum: 12 }, ]
1
sadfQED2 2022-08-11 15:03:56 +08:00 via Android
select uid,type,sum(num) from xxxx group by uid,type
|
2
ThunderMonkey 2022-08-11 15:06:09 +08:00
SELECT
uid, sum(case when type = 0 then num else 0 end) as type_0, sum(case when type = 1 then num else 0 end) as type_1, sum(case when type = 2 then num else 0 end) as type_2 FROM table group by uid |
3
Danswerme OP |