MySQL视图“扁平化”数据

时间:2012-03-09 21:52:19

标签: mysql sql aggregate-functions

我有下表:

group_id    amount  type
1           10      1
1           2       1
1           5       2
1           4       3
2           5       1

我正在寻找一个视图,它将聚合此表中的数据,以便视图生成类似的内容,并希望以动态方式执行此操作:

group_id    type1_amount    type2_amount    type3_amount
1           12              5               4
2           1               NULL            NULL

我的偏好是在MySQL中使用一个视图(如果你有一个更好的选择我可以听到它),并且MySQL中视图的大限制是不允许在FROM子句中使用子选项。

1 个答案:

答案 0 :(得分:4)

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