2012-11-02 75 views
0

可能重複:
SQL Server dynamic PIVOT query?Transpose /將不同的行屬性轉換爲列和組另一個屬性?

是否有可能爲下表上執行一個查詢:

Game Player Goals 
----- ------ ------ 
Game1 John 1 
Game1 Paul 0 
Game1 Mark 2 
Game1 Luke 1 
Game2 John 3 
Game2 Paul 1 
Game2 Luke 1 
Game3 John 0 
Game3 Mark 2 

這給這樣的結果:

Game John Paul Mark Luke 
----- ---- ---- ---- ---- 
Game1 1  0  2  1 
Game2 3  1  -  1 
Game3 0  -  2  - 

它將每個不同的玩家變成一個專欄,並將遊戲分組,讓每位玩家獲得每個遊戲的目標。

+0

[SQL Server的動態PIVOT查詢?](http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query),或在SQL動態列[支點服務器](http://stackoverflow.com/questions/7822004/pivots-with-dynamic-columns-in-sql-server) – RichardTheKiwi

回答

3

您可以使用PIVOT函數。如果你有一個著名的列數,那麼你可以硬編碼值:

select * 
from 
(
    select game, player, goals 
    from yourtable 
) src 
pivot 
(
    sum(goals) 
    for player in ([John], [Paul], [Mark], [Luke]) 
) piv 
order by game 

SQL Fiddle with Demo

如果你有一個未知的列數,那麼你可以使用動態SQL:

DECLARE @cols AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX) 

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(player) 
        from yourtable 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT game, ' + @cols + ' from 
      (
       select game, player, goals 
       from yourtable 
      ) x 
      pivot 
      (
       sum(goals) 
       for player in (' + @cols + ') 
      ) p ' 

execute(@query) 

SQL Fiddle with Demo

+0

這是優秀的,完美的作品。謝謝! – edezzie

2
select game, 
    sum(case when player = 'john' then goals else 0 end) as john, 
    sum(case when player = 'paul' then goals else 0 end) as paul, 
    sum(case when player = 'mark' then goals else 0 end) as mark, 
    sum(case when player = 'luke' then goals else 0 end) as luke 
from t 
group by game 
order by game 
相關問題