在sql中的pivot和concatenate

时间:2017-06-26 11:55:07

标签: sql sql-server tsql pivot

我有很多关于数据透镜的例子,但我需要像下面这样的数据透视和连接。我是sql的新手。请指导我,我需要国家名称和年份的动态支点。

我的桌子像

Country  | year  | played  |  win | loss
----------------------------------------
India    | 2005  | 40      | 15   |  25  
India    | 2006  | 29      | 10   |  19  
India    | 2007  | 52      | 32   |  20  
China    | 2005  | 100     | 68   |  32  
China    | 2006  | 90      | 60   |  30  
China    | 2007  | 110     | 70   |  40

现在我需要像

这样的结果表
Country | Stat   | 2005  | 2006 |2007
-----------------------------------
India   | played | 40    | 29   | 52  
        |  win   | 15    | 10   | 30  
        |  loss  | 25    | 19   | 22  
China   | played | 100   |  90  | 110  
        |  win   |  68   |  60  |  70  
        |  loss  |  32   |  30  |  40

1 个答案:

答案 0 :(得分:4)

两种快速方法

1)静态

Select Country=choose(Seq,Country,'','')
      ,Stat
      ,[2005],[2006],[2007]
 From (
        Select A.[Country]
              ,A.[Year]
              ,B.*
         From  YourTable A
         Cross Apply ( values (1,'played',played)
                             ,(2,'win'   ,win)
                             ,(3,'loss'  ,loss)
                     ) B (Seq,Stat,Value)
      ) A
 Pivot (max([Value]) For [Year] in ([2005],[2006],[2007]) ) p

2)动态

Declare @SQL varchar(max) = ''
Select @SQL = Stuff((Select Distinct ','+QuoteName(Year) From YourTable Order By 1 For XML Path('')),1,1,'')
Select @SQL = '
Select Country=choose(Seq,Country,'''','''')
      ,Stat
      ,'+ @SQL +'
 From (
        Select A.[Country]
              ,A.[Year]
              ,B.*
         From  YourTable A
         Cross Apply ( values (1,''played'',played)
                             ,(2,''win''   ,win)
                             ,(3,''loss''  ,loss)
                     ) B (Seq,Stat,Value)

      ) A
 Pivot (max([Value]) For [Year] in (' + @SQL  + ') ) p'
Exec(@SQL);

返回

enter image description here