如何组合来自CTE的多个PIVOTed结果

时间:2016-06-21 00:12:45

标签: sql tsql reporting-services common-table-expression

我有两个转动的cte:

        ;WITH cte_yoyComparison
AS
            (
SELECT      b.YearNum, 
            --b.MonthNum,
            b.MonthName,
            sum(Premium) as Premium 
            FROM tblCalendar b  
LEFT JOIN Test_Plaza_ProductionReport  a ON b.MonthNum=MONTH(a.EffectiveDate) AND b.YearNum=YEAR(a.EffectiveDate)
WHERE       YEAR(EffectiveDate) <> 2017
GROUP BY    b.YearNum, 
            --b.MonthNum,
            b.MonthName
            )



select [YearNum] as [YearNum], [January], [February],[March], [April],[May],[June],[July], [August], [September],[October],[November],[December] from ( select * from cte_yoyComparison) src
PIVOT
    (
            sum(src.Premium)
            FOR src.[MonthName] IN ([January], [February],[March], [April],[May],[June],[July], [August], [September],[October],[November],[December])
    ) as [PivotTable]
    order by YearNum DESC 

它的结果看起来像enter image description here

第二个:

    WITH cte_yoyComparison
AS
        (
SELECT  Year(EffectiveDate) AS EffectiveYear,
        Month(EffectiveDate) AS EffectiveMonth,
        sum(Premium) as Premium 
FROM    Test_Plaza_ProductionReport 
WHERE YEAR(EffectiveDate) <> 2017
GROUP BY      Year(EffectiveDate),
                Month(EffectiveDate)
            ),
cte_Calendar
as
(
SELECT YearNum, MonthName, Premium FROM tblCalendar b  
LEFT JOIN cte_yoyComparison a ON b.MonthNum=a.EffectiveMonth AND b.YearNum=a.EffectiveYear
WHERE b.YearNum<>2017
)  --select * from cte_yoyComparison
,
cte_Premium
as
(
select [YearNum] as [YearNum], [January], [February],[March], [April],[May],[June],[July], [August], [September],[October],[November],[December] from ( select * from cte_Calendar) src
PIVOT
    (
            sum(src.Premium)
            FOR src.[MonthName] IN ([January], [February],[March], [April],[May],[June],[July], [August], [September],[October],[November],[December])
    ) as [PivotTable]
    --ORDER BY [YearNum] DESC
)
 Select Cast(upyear.[YearNum] as varchar) + ' vs ' + Cast(downyear.[YearNum] as varchar) + ' % Change' [YearNum], 
 (upyear.January/downyear.January - 1) January, (upyear.February/downyear.February - 1) February,
 (upyear.March/downyear.March - 1) March,
 (upyear.April/downyear.April - 1) April,
 (upyear.May/downyear.May - 1) May,
 (upyear.June/downyear.June - 1) June,
 (upyear.July/downyear.July - 1) July,
 (upyear.August/downyear.August - 1) August,
 (upyear.September/downyear.September - 1) September,
 (upyear.October/downyear.October - 1) October,
 (upyear.November/downyear.November - 1) November,
 (upyear.December/downyear.December - 1) December
 from cte_Premium upyear inner join cte_Premium downyear
 ON upyear.[YearNum]=downyear.[YearNum] +1
 order by [YearNum] DESC

结果将如下所示: enter image description here

如何将这些cte组合在一起以获得如下结果: enter image description here

0 个答案:

没有答案