假设查询的结果如下所示:
+----+---------+--------+
| id | count | type |
+----+---------+--------+
| 1 | 20 | a |
| 1 | 30 | b |
| 1 | 10 | c |
| 2 | 05 | a |
| 2 | 20 | b |
| 2 | 40 | c |
+----+---------+--------+
和预期的结果:
+----+---------+--------+------+
| id | a | b | c |
+----+---------+--------+------+
| 1 | 20 | 30 | 10 |
| 2 | 05 | 20 | 40 |
+----+---------+--------+------+
我知道一些使用 Cursor、Variables、Join 等的复杂解决方案。我想找到最有效的解决方案,否则我会从应用层处理它。
最佳答案
一种方法使用条件聚合:
select id,
sum(case when type = 'a' then count else 0 end) as a,
sum(case when type = 'b' then count else 0 end) as b,
sum(case when type = 'c' then count else 0 end) as c
from t
group by id;
关于mysql - 按一个字段分组并将所有其他字段放在 SQL 行中的高效查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40871600/