Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Pivot, NestedPivot, unPivot?

$
0
0
Trying to work out some code that involves a pivot, and I'm stuck. Grateful for some assistance...Source table has:[code][font="Courier New"]NUMBER MileStone ForecastDate ActualDate StatusFlag1 A 1/1/2015 T1 B 2/1/2014 1/1/2015 F 1 C L2 A 3/1/2015 Q[/font][/code]What I need to end up with is a table like:[code][font="Courier New"]JobNo MilestoneA_Fcst MilestoneA_Act MileStoneA_Flag MilestoneB_Fcst MilestoneB_Act MileStoneB_Flag MilestoneC_Fcst MilestoneC_Act MileStoneC_Flag1 1/1/15 T 2/1/14 1/1/15 F T[/font][/code]I can get the pivot to work and produce the date columns, but it's the flag column that I can't get to work.[code="sql"]SELECT *FROM ( SELECT NUMBER AS JobNo, Milestone + 'F' AS TaskCode, CAST(forecastdate AS SMALLDATETIME) AS TaskDate FROM Milestonetable AS FcstDateQuery UNION SELECT NUMBER AS JobNo, Milestone + 'A' AS TaskCode, CAST(actualdate AS SMALLDATETIME) AS TaskDate FROM Milestonetable AS ActDateQuery ) AS TaskDateQueryPIVOT(MAX(TaskDate) FOR TaskCode IN ( [MileStoneA_Act], [MileStoneA_Fcst], [MileStoneB_Act], [MileStoneB_Fcst], [MileStoneC_Act], [MileStoneC_Fcst] )) AS Piv[/code]Everything I've tried didn't come out right in the end. Figure I need some sort of nested pivot but I can't figure out how to do it.

Viewing all articles
Browse latest Browse all 3145

Trending Articles