2017-02-01 78 views
0

我與SQL Server 2012的工作,我的表是這樣的:在SQL Server中,如何在列中顯示錶行值?

Customer Status   StatusType 
---------------------------------------- 
    3   Ok    personalInfo 
    3   Pending  FinancialInfo 
    3   NeedUpdate  CompanyInfo 

要在這裏得到的結果,我需要一個SQL查詢:

Customer PersonalInfo FinancialInfo CompanyInfo 
--------------------------------------------------------- 
    3  Ok    Pending   NeedUpdate 
+0

只需要'Pivot'或查詢將行轉換爲列即可。就是這樣。 –

回答

1
CREATE TABLE #Table1 
    ([Customer] int, [Status] varchar(10), [StatusType] varchar(13)) 
; 

INSERT INTO #Table1 
    ([Customer], [Status], [StatusType]) 
VALUES 
    (3, 'Ok', 'personalInfo'), 
    (3, 'Pending', 'FinancialInfo'), 
    (3, 'NeedUpdate', 'CompanyInfo')  
SELECT * 
    FROM #Table1 
    PIVOT (max([status]) 
     for [StatusType] in ([PersonalInfo], [FinancialInfo], [CompanyInfo])) AS pvt 

輸出

Customer PersonalInfo FinancialInfo CompanyInfo 
3    Ok    Pending   NeedUpdate 

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

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[StatusType]) 
      FROM #Table1 c 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT customer, ' + @cols + ' from 

       #Table1 
    PIVOT (max([status]) 
     for [StatusType] in ([PersonalInfo], [FinancialInfo], [CompanyInfo])) AS pvt' 


exec(@query) 
+0

有一個問題,運算符中的Pivot,我的StatusType不固定,它們是動態的 – shamim

相關問題