2017-10-28 3 views
-1

Ich habe folgende Daten:Wie Spalten aus einer Liste von Werten erstellen

Table 1 
Row ID  Value  Cost 
1  1  Priority 1 10,000 
2  2  Priority 2 9,000 
3  3  Priority 3 8,000 
4  4  Priority 4 6,000 

Table 2 
Row Name Priority Cost 
1  Jon  1   10,000 
2  Bob  3   8,000 
3  Dan  4   7,000 
4  Steve 2   9,000 
5  Bill 3   8,000 
... 

Ich mag die Tabelle wie folgt aussehen:

Table 3 
Row Name  Priotity 1  Priority 2  Priority 3  Priority 4 
1 Jon  10,000 
2 Bob         8,000 
3 Dan             7,000 
4 Steve     9,000 
5 Bill         8,000 
... 

Wie ich Zeilen aus Tabelle erstellen 1 als Spalten und füllen Sie die Ausgabe wie in Tabelle 3 gezeigt.

Ich hoffe, das ist nicht so einfach wie es klingt, aber mein SQL ist schrecklich!

+2

Google: „ dynamische Pivot“. –

Antwort

0

können Sie dies für dynamische Pivot-Tabelle versuchen.

DECLARE @columns VARCHAR(8000) 


SELECT @columns = COALESCE(@columns + ',[' + cast(Value as varchar) + ']', 
'[' + cast(Value as varchar)+ ']') 
FROM Table1 
GROUP BY Value 

DECLARE @query VARCHAR(8000) 
SET @query = 'with Priorites as 
(select a.Name,b.Value,b.Cost from Table2 a left join Table1 b on a.Priority =b.id) 
SELECT * 
FROM Priorites 
PIVOT 
(
MAX(Cost) 
FOR [Value] 
IN (' + @columns + ') 
) 
AS p' 

EXECUTE(@query) 

Hier ist der Link, um weitere Informationen http://www.tsqltutorials.com/pivot.php

0

Pivot ist in dieser Art von Szenario immer nützlich, aber wenn die Ist-Daten sind so einfach, wie es in Frage ist (wie es nur 4 einzigartige Priority ist und/oder nur 1 Priorität zu einem bestimmten Benutzer zugeordnet ist), dann können Sie diese Aufgabe mit folgenden Abfrage erreichen:

select t.row,t.name 
    (case when t.priority = 1 then t.cost 
     else ' ' 
    end 
) as Priority1, 
    (case when t.priority = 2 then t.cost 
     else ' ' 
    end 
) as Priority2, 
    (case when t.priority = 3 then t.cost 
     else ' ' 
    end 
) as Priority3, 
    (case when t.priority = 4 then t.cost 
     else ' ' 
    end 
) as Priority4 
From 
    (select Row,name,priority,cost 
    from Table2 
    group by name) t 
group by t.name; 
Verwandte Themen