Sql server:如何PIVOT行到列标题?

时间:2017-08-31 15:19:14

标签: sql sql-server tsql sql-server-2008-r2 pivot

我希望PIVOT将多个数据行添加到列中通过将列区域修复为标题列 (3区域是cd,gk,kl)

示例 表:details_data

code | name   | team | score | rank | area
w001 | name01 | AA01 | 10    | 1    | CD
w002 | name02 | AA04 | 05    | 5    | CD
w008 | name08 | AA02 | 08    | 2    | GK
w011 | name11 | AA05 | 15    | 3    | GK
w014 | name14 | AA06 | 10    | 1    | KL
w020 | name20 | AA07 | 20    | 5    | KL

我想重新更改列(cd,gk,kl)到标题:

cd_code|cd_name|cd_team|cd_score|cd_rank|gk_code|gk_name|gk_team|gk_score|kl......
w001   |name01 | AA01  | 10     | 1     |w008   |name08 | AA02  | 08     |kl......
w002   |name02 | AA04  | 05     | 5     |w011   |name11 | AA05  | 15     |kl......    
................
................

我希望将行行区域转到列标题。 请帮我。谢谢提前;)

1 个答案:

答案 0 :(得分:1)

也许是这样的?

示例

;with cte0 as (
    Select * 
          ,CN = Dense_Rank() over (Order by area) 
          ,RN = Row_Number() over (Partition by area Order by area,Code)
     From  details_data 
     )
Select cd_code  = max(case when CN=1 then code end)
      ,cd_name  = max(case when CN=1 then name end)
      ,cd_team  = max(case when CN=1 then team end)
      ,cd_score = max(case when CN=1 then score end)
      ,cd_rank  = max(case when CN=1 then [rank] end)
      ,gk_code  = max(case when CN=2 then code end)
      ,gk_name  = max(case when CN=2 then name end)
      ,gk_team  = max(case when CN=2 then team end)
      ,gk_score = max(case when CN=2 then score end)
      ,gk_rank  = max(case when CN=2 then [rank] end)
      ,kl_code  = max(case when CN=3 then code end)
      ,kl_name  = max(case when CN=3 then name end)
      ,kl_team  = max(case when CN=3 then team end)
      ,kl_score = max(case when CN=3 then score end)
      ,kl_rank  = max(case when CN=3 then [rank] end)
 From  cte0
 Group By RN

<强>返回

enter image description here