La mise en œuvre d'une requête PIVOT
-
16-10-2019 - |
Question
Comment puis-je faire pivoter l'instruction SELECT suivante:
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
Cette déclaration donne le jeu de résultats qui suit:
CID OverviewText RAGStatusText
--- ------------ -------------
153 Cost Green
154 Requirements Yellow
155 Schedule NULL
156 Technical NULL
157 Testing NULL
Mais, je veux revenir une seule ligne avec 10 valeurs, comme indiqué ci-dessous:
----------------------------------------------------------------------------------------------
| Cost | Green | Requirements | Yellow | Schedule | NULL | Technical | NULL | Testing | NULL |
----------------------------------------------------------------------------------------------
Puis-je pivotent sur CID
?
La solution
Je ne sais pas si c'est exactement ce que vous voulez. Mais il donne le résultat attendu. Notez que vous pouvez renommer les colonnes que vous s'il vous plaît.
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;
Licencié sous: CC-BY-SA avec attribution
Non affilié à dba.stackexchange