如何使用旋转的SELECT语句UNION ALL两个CTE

时间:2016-06-27 16:22:51

标签: sql tsql reporting-services

我有两个CTE的结果,我需要他们到UNION ALL来接收这样的结果: enter image description here

;WITH cte_yoyComparison
AS
            (
SELECT      b.YearNum,  
            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.MonthName
            )
            ,
    cte_yoyComparison1
AS
        (
SELECT  b.YearNum,
        b.MonthName,
        ISNULL(sum(case when TransactionType IN ('Policy', 'Reinstatement') then 1 ELSE 0 END),0) as Bound--,   
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.MonthName,
            b.MonthNum
            )

            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]

UNION ALL 

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

我得到错误:

  

Msg 102,Level 15,State 1,Line 31语法不正确&#39 ;;&#39;。

如何以正确的方式实现这一目标?感谢

0 个答案:

没有答案