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

可以在MySQL中聚合这样的行吗?,mysql,sql,Mysql,Sql,根据下表中的车型 +-------+----+-------+ | model | id | total | +-------+----+-------+ | civic | 1 | 27 | | civic | 3 | 11 | | crv | 3 | 5 | +-------+----+-------+ 是否可以查询以获得此结果 +-------+-----+-----+-----+ | model | id1 | id2 | id3 | +-------+-

根据下表中的车型

+-------+----+-------+
| model | id | total |
+-------+----+-------+
| civic |  1 |   27  |
| civic |  3 |   11  |
| crv   |  3 |    5  |
+-------+----+-------+
是否可以查询以获得此结果

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

这是一个pivot查询。在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;

答案是肯定的。将3个案例添加到您的选择列表中,每个id对应一个案例。您正在查找数据透视表。这个类似的问题:将提供一个良好的起点。