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

efficient query to group by one field and put all other fields in the row SQL

想象一下查询的结果如下所示:

+----+---------+--------+
| 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;