2017-05-21 148 views
1

請看下面的例子:顯示多行到一行在SQL Server

enter image description here

我想所有這些行合併爲一個排,注意行的數​​量是動態的!

輸出應該是這樣的:

enter image description here

謝謝

+0

當你用Google搜索各種明確的聲明提出質疑,你發現了什麼? PS這是一個常見問題,研究「旋轉」。 – philipxy

+0

我沒有在網上找到相同的例子! – tollamie

+0

您最終會得到動態列號,通常它根本不可用。你想要顯示什麼順序?如果沒有提供訂單,它會默認存儲訂單,如堆 –

回答

1

Declare @SQL varchar(max) = '' 
Set @SQL = Stuff((Select Distinct ',' +QuoteName('C'+cast(RN as varchar(25))) 
            +','+QuoteName('P'+cast(RN as varchar(25))) 
        From (Select Distinct RN=Row_Number() over (Order By Pays) From YourTable) A 
        Order by 1 For XML Path('')),1,1,'') 

Set @SQL = ' 
Select ' + replace(replace(@SQL,'[P','Pays=[P'),'[C','Count=[C') + ' 
From (
     Select B.* 
     From (
       Select *,RN = Row_Number() over (Order By Pays) 
       From YourTable 
       ) A 
     Cross Apply (values (''P''+cast(A.RN as varchar(25)),A.Pays) 
          ,(''C''+cast(A.RN as varchar(25)),cast(A.Count as varchar(50))) 
        ) B (Item,Value) 
    ) A 
Pivot (max(value) For [Item] in (' + @SQL + ')) p' 
Exec(@SQL); 

返回

enter image description here


如果有幫助,生成的SQL是這樣的:你

Select Count=[C1],Pays=[P1],Count=[C2],Pays=[P2],Count=[C3],Pays=[P3],Count=[C4],Pays=[P4] 
From (
     Select B.* 
     From (
       Select *,RN = Row_Number() over (Order By Pays) 
       From YourTable 
       ) A 
     Cross Apply (values ('P'+cast(A.RN as varchar(25)),A.Pays) 
          ,('C'+cast(A.RN as varchar(25)),cast(A.Count as varchar(50))) 
        ) B (Item,Value) 
    ) A 
Pivot (max(value) For [Item] in ([C1],[P1],[C2],[P2],[C3],[P3],[C4],[P4])) p 
+0

非常感謝,你的代碼幫了我很多 – tollamie

+0

@tollamie對它有幫助 –