Implementazione di una query PIVOT
-
16-10-2019 - |
Domanda
Come posso ruotare la seguente istruzione SELECT:
SELECT sc.CID,
sc.CodeName as OverviewText,
scRAG.CodeName as RAGStatusText
FROM StatusCode sc
LEFT OUTER JOIN ProjectOverview po
ON sc.CID = po.ProjectOverviewCID
AND po.ProjectId = 180
LEFT OUTER JOIN StatusCode scRAG
ON po.RAGStatusCID = scRAG.CID
WHERE sc.SCID = 18
Tale dichiarazione produce il set di risultati che segue:
CID OverviewText RAGStatusText
--- ------------ -------------
153 Cost Green
154 Requirements Yellow
155 Schedule NULL
156 Technical NULL
157 Testing NULL
Ma, voglio che ritorni una sola riga con 10 valori, come mostrato sotto:
----------------------------------------------------------------------------------------------
| Cost | Green | Requirements | Yellow | Schedule | NULL | Technical | NULL | Testing | NULL |
----------------------------------------------------------------------------------------------
Posso perno su CID
?
Soluzione
Non sono sicuro se questo è esattamente quello che vuoi. Ma dà il risultato previsto. Nota: è possibile rinominare le colonne a piacimento.
SET NOCOUNT ON
declare @t table(
cid int,
OverviewText varchar(15),
RAGStatusText varchar(15)
)
insert into @t values (153, 'Cost', 'Green');
insert into @t values (154, 'Requirements', 'Yellow');
insert into @t values (155, 'Schedule', 'NULL');
insert into @t values (156, 'Technical', 'NULL');
insert into @t values (157, 'Testing', 'NULL');
Select
[153|1] as [xyz],
[153|2],
[154|1],
[154|2],
[155|1],
[155|2],
[156|1],
[156|2],
[157|1],
[157|2]
FROM (
select CAST(cid as varchar) + '|1' type, OverviewText text from @t
Union
select CAST(cid as varchar) + '|2' type, RAGStatusText text from @t
) as SourceTable
Pivot(
min(text)
for type in ([153|1],[153|2], [154|1],[154|2], [155|1],[155|2], [156|1],[156|2], [157|1],[157|2])
) as PivotTable;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a dba.stackexchange