2016-07-20 15 views
-1

Ich habe eine Tabelle Tabelle, die einige Spalten haben, und ich möchte Spaltenwerte als Spalten für eine andere Tabelle konvertieren.Zeilen in Spalten in neue Tabelle konvertieren

Ich füge einen Screenshot meiner Anforderung an.

Die obere Tabelle ist meine Haupttabelle sagen Table1 und die unten ist meine erforderliche Tabelle. Dank

+0

können Sie einfach mysql rohen zu Spalte mit case Anweisung –

+0

@Jens - Sorry, dass das versehentlich war Ich benutze SQL Server 2012 –

+1

Mögliche Duplikat von [Effizient Zeilen in Spalten in SQL Server konvertieren] (http: // Stackoverflow. com/questions/15745042/effizient-konvertieren-rows-to-columns-in-sql-server) – Ash

Antwort

0

Ich denke, Schwenk genug sein wird:

SELECT * 
FROM (
    SELECT [Action], [Key], 'Old' + Old as [a], OldValue as [Value] 
    FROM Table1 
    UNION ALL 
    SELECT [Action], [Key], 'New' + New, NewValue 
    FROM Table1 
    ) as p 
PIVOT (
    MAX([Value]) FOR [a] IN ([OldCol1],[OldCol2],[OldCol3],[NewCol1],[NewCol2],[NewCol3],[NewCol45]) 
) as pvt 

Ausgang:

Action Key OldCol1 OldCol2 OldCol3 NewCol1 NewCol2 NewCol3 NewCol45 
I  123 NULL NULL NULL NULL NULL NULL Sun 
U  123 Dog  Cat  Honey Dog  Mouse Bee  NULL 

Wenn es viele Old und ‚New` Werte dann müssen Sie dynamischen SQL

+0

danke es funktioniert und jetzt weiß ich wo war mein Fehler. –

+0

Großartig, wenn meine Antwort Ihnen geholfen hat! :) – gofr1

1

Während das vorgeschlagene Duplikat einen Teil des Weges dorthin bekommen wird, müssen Sie eigentlich pivotieren und dann pivotieren, so.

(Oh und bitte nicht Bilder DDL geschätzt und spart uns die Eingabe und/oder zu erraten..)

CREATE TABLE #Test(Action char, [Key] INT, Old varchar(5), OldValue varchar(5), New varchar(5), NewValue varchar(5)); 

INSERT INTO #Test VALUES 
('U', 123, 'Col1','Dog','Col1','Dog'), 
('U', 123, 'Col2','Cat','Col2','Mouse'), 
('U', 123, 'Col3','Honey','Col3','Bee'), 
('I', 123, NULL,NULL,'Col45','Sun'); 


SELECT PVT.Action 
     ,PVT.[Key] 
     ,PVT.OldCol1 
     ,PVT.OldCol2 
     ,PVT.OldCol3 
     ,PVT.NewCol1 
     ,PVT.NewCol2 
     ,PVT.NewCol3 
     ,PVT.NewCol45 FROM (
SELECT [Action] 
     ,[Key] 
     ,Label 
     ,Value 
FROM #Test 
CROSS APPLY (VALUES ('Old'+Old, OldValue), ('New'+New, NewValue)) c(label, value) 
)src 
PIVOT 
(
MAX(VALUE) FOR Label IN (OldCol1, NewCol1, OldCol2, NewCol2, OldCol3, NewCol3, NewCol45) 
)PVT 
ORDER BY PVT.Action Desc 


Action Key   OldCol1 OldCol2 OldCol3 NewCol1 NewCol2 NewCol3 NewCol45 
------ ----------- ------- ------- ------- ------- ------- ------- -------- 
U  123   Dog  Cat  Honey Dog  Mouse Bee  NULL 
I  123   NULL NULL NULL NULL NULL NULL Sun 

(2 row(s) affected) 
+0

dies funktioniert auch, aber grof1 's Lösungen war etwas in der Nähe, wo ich steckte. danke trotzdem –

Verwandte Themen