2016-06-21 81 views
0

我需要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 

它的結果看起來像這樣:enter image description here

但我需要這樣的: enter image description here

我試圖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 
+0

爲什麼在'ORDER BY'中添加'sortField'?這不會給出相同的結果嗎? – BJones

+0

@bjones否...如果您不包含sortField,您將並排獲取年份行。這個分組表格每個表格產生一個分離的組。 –

+0

我明白了。我想我對這個問題感到困惑。 – BJones