我需要UNION ALL多个临时表,每个必须按YearNum DESC排序。
;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但仍然没有运气。
答案 0 :(得分:2)
首先请注意,这种事情通常是在UI上处理而不是在db 中。
但这可能会解决您的问题
SELECT * -- or put the fieldList without the *sortfield*
FROM (
select '1' sortField, * from #TempData
union all
select '2' sortField, * from #TempData1
) T
ORDER BY sortField, YearField DESC