V 友们请教一个 SQL 语句的写法

2022-08-11 14:48:53 +08:00
 Danswerme

表是这样的:

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 }, ]

559 次点击
所在节点    问与答
3 条回复
sadfQED2
2022-08-11 15:03:56 +08:00
select uid,type,sum(num) from xxxx group by uid,type
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
Danswerme
2022-08-11 15:15:55 +08:00
@sadfQED2
@ThunderMonkey 谢谢两位

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/872165

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX