我有下表:
group_id amount type
1 10 1
1 2 1
1 5 2
1 4 3
2 5 1
我正在寻找一个 View 来聚合此表中的数据,以便该 View 生成类似这样的内容,并且希望能够以动态方式执行此操作:
group_id type1_amount type2_amount type3_amount
1 12 5 4
2 1 NULL NULL
我的偏好是使用 MySQL 中的 View (如果您有更好的选择,我很乐意听取它),并且 MySQL 中 View 的一大限制是不允许在 FROM 子句中进行子选择。
最佳答案
SELECT
group_id,
SUM(CASE WHEN type = 1 THEN amount END) AS type1_amount,
SUM(CASE WHEN type = 2 THEN amount END) AS type2_amount,
SUM(CASE WHEN type = 3 THEN amount END) AS type3_amount
FROM your_table
GROUP BY group_id
关于MySQL查看 "flattens"数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9641485/