2016-07-14 75 views
0

我想轉置下面的表格,以便第一列(tabLabel)成爲頁眉。我需要動態執行此操作,因爲行數未知。我已經看到了關於動態樞紐的帖子,但我不完全明白這將如何完成。動態數據透視SQL列數據到頁眉

tabLabel   documentId recipientId  Date value 
Street Address   1   1   NULL 123 mockingbird lane 
City     1   1   NULL city 
Patient Phone   1   1   NULL 999-999-9999 
Responsible Phone  1   1   NULL 999-999-9999 
Gross Income   1   1   NULL 999 
Monthly Mortgage/Rent 1   1   NULL 100 
Monthly Auto   1   1   NULL 200 

最終版本:

Street Address   City Patient Phone Responsible Phone Gross Income Monthly Mortage/Rent Monthly Auto documentId recipientId Date 
123 mockingbird lane city 999-999-9999 999-999-9999  999   100     200   1    1   NULL 

選擇查詢的原始表:

SELECT [tabLabel] 
    ,[documentId] 
    ,[recipientId] 
    ,[Date] 
    ,[value] 
    FROM [zDocusign_Document_Tab_Fields] 
+0

你能做到這一點在你的代碼?這會更容易閱讀。 – user2023861

+0

@ user2023861你的意思是插入我的創建表或插入語句? –

+0

我的意思是,如果您正在將這些數據讀入某個應用程序,則可以將數據轉到那裏。我知道在C#中這樣做會比我在Google上搜索「sql server dynamic pivot」時看到的要容易得多。 – user2023861

回答

2

動態SQL

-- Build colums 
DECLARE @cols NVARCHAR(MAX) 
SELECT @cols = STUFF((
    SELECT DISTINCT ',' + QUOTENAME([tabLabel]) 
    FROM zDocusign_Document_Tab_Fields 
    FOR XML PATH('') 
), 1, 1, '') 
-- Selecting as FOR XML PATH will give you a string value with all of the fields combined 
-- separated by comma. Stuff simply removes the first comma. 
-- Quotename wraps the [tabLabel] value in brackets to allow for spaces in column name 
-- You end up with 
-- [City],[Gross Income],[Monthly Auto],[Monthly Mortgage/Rent],[Patient Phone],[Responsible Phone],[Street Address] 

-- Build sql 
DECLARE @sql NVARCHAR(MAX) 
SET  @sql = N' 
    SELECT ' + @cols +' 
    FROM zDocusign_Document_Tab_Fields 
    PIVOT (
     MAX([value]) 
     FOR [tabLabel] IN (' + @cols + ') 
    ) p 
' 

-- Execute Sql 
EXEC(@sql) 
+0

非常感謝!立即工作! –