我需要UNION ALL多個temptables,並且每個都必須按YearNum DESC排序。如何在組合多個#表格時使用Union All和GROUP BY
;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] into #TempData 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]
IF OBJECT_ID('tempdb..#TempData1') IS NOT NULL
DROP TABLE #TempData1
;WITH cte_yoyComparison
AS
(
SELECT b.YearNum,
--b.MonthNum,
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] into #TempData1 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]
order by YearNum DESC
select * from #TempData
union all
select * from #TempData1
我試圖ROWNUMBER添加到每個CTE,但仍然沒有運氣。
所以數據是確定的,只是順序錯了嗎? –