是否可以在MySQL中聚合这样的行?

时间:2015-09-09 14:00:03

标签: mysql sql

使用下表中的车型,

+-------+----+-------+
| model | id | total |
+-------+----+-------+
| civic |  1 |   27  |
| civic |  3 |   11  |
| crv   |  3 |    5  |
+-------+----+-------+

是否可以查询以获得此结果?

+-------+-----+-----+-----+
| model | id1 | id2 | id3 |
+-------+-----+-----+-----+
| civic |  27 |   0 |  11 |
| crv   |   0 |   0 |   5 |
+-------+-----+-----+-----+

1 个答案:

答案 0 :(得分:2)

这是一个透视查询。在MySQL中处理这种情况的一种方法是条件聚合:

select model,
       max(case when id = 1 then total else 0 end) as id1,
       max(case when id = 2 then total else 0 end) as id2,
       max(case when id = 3 then total else 0 end) as id3
from carmodels t
group by model;