2016-06-21 1 views
0

複数のtemptablesを結合する必要があり、それぞれをYearNum DESCでソートする必要があります。複数の#Tablesを組み合わせるときに、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

私はCTEが、まだ運のそれぞれにRowNumber関数を追加しようとしました。

+0

ので、データがOKである、唯一の順番が間違っていますか? –

答えて

2

この種のものは、通常、dbにないのUIのハンドルです。

しかし、これはあなたの問題を解決することがあり

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

なぜ 'sortField'を' ORDER BY'に追加しますか?それは同じ結果をもたらしませんか? – BJones

+0

@bjonesいいえ... sortFieldを含めないと、年の行が並べて表示されます。この結果、各テーブルはグループ分けされます。 –

+0

私は参照してください。私はその質問に私が混乱していたと思う。 – BJones

関連する問題