2016-11-29 20 views
0

试想一个查询的结果是类似如下:高效的查询到组,并把所有其他领域中的行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等很复杂的解决方案。我想找到最高效的解决方案,否则我会从应用程序层处理它。

+0

我删除了基于证据占优势的T-SQL。您应该仅使用您正在使用的数据库进行标记。 –

+0

[SQL Transpose Rows as Columns]的可能重复(http://stackoverflow.com/questions/2099198/sql-transpose-rows-as-columns) – CGritton

回答

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;