Transpose / Pivot将不同的行属性作为列并将另一个属性分组?

时间:2012-11-02 01:48:27

标签: sql sql-server pivot

  

可能重复:
  SQL Server dynamic PIVOT query?

是否可以对下表执行查询:

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       -

它将每个不同的玩家变成一个列,并将游戏分组给每个玩家的每个游戏目标。

2 个答案:

答案 0 :(得分:5)

您可以使用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

答案 1 :(得分: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