2016-11-29 19 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;