高效查询按一个字段分组,并将所有其他字段放在SQL行中

时间:2016-11-29 17:03:12

标签: mysql sql pivot mariadb

想象一下,查询结果如下:

+----+---------+--------+
| 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等复杂的解决方案。我想找到最有效的解决方案,否则我将从应用层处理它。

1 个答案:

答案 0 :(得分:4)

一种方法使用条件聚合:

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;