2016-07-14 8 views
0

Ich möchte die folgende Tabelle so transponieren, dass die erste Spalte (TabLabel) wird die Kopfzeile. Ich muss das dynamisch machen, weil die Anzahl der Zeilen unbekannt ist. Ich habe Posts auf dynamischen Pivots gesehen, aber ich verstehe nicht ganz, wie dies geschehen würde.Dynamic Pivot SQL-Spalte Daten zu Header

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 

Endfassung:

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 

Wählen Sie Abfrage auf Original-Tabelle:

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

Können Sie es in Ihrem Code zu tun? Es wäre viel einfacher zu lesen. – user2023861

+0

@ user2023861 meinst du meine create table oder eine insert statement einzufügen? –

+0

Ich meine, wenn Sie diese Daten in eine Anwendung lesen, können Sie die Daten dort drehen. Ich weiß, dass dies in C# zu tun wäre viel einfacher als das, was ich sah, wenn ich "sql Server dynamische Pivot" googelte – user2023861

Antwort

2

dynamische 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

Vielen Dank! Sofort gearbeitet! –