我有两个转动的cte:
;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] 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]
order by YearNum DESC
第二个:
WITH cte_yoyComparison
AS
(
SELECT Year(EffectiveDate) AS EffectiveYear,
Month(EffectiveDate) AS EffectiveMonth,
sum(Premium) as Premium
FROM Test_Plaza_ProductionReport
WHERE YEAR(EffectiveDate) <> 2017
GROUP BY Year(EffectiveDate),
Month(EffectiveDate)
),
cte_Calendar
as
(
SELECT YearNum, MonthName, Premium FROM tblCalendar b
LEFT JOIN cte_yoyComparison a ON b.MonthNum=a.EffectiveMonth AND b.YearNum=a.EffectiveYear
WHERE b.YearNum<>2017
) --select * from cte_yoyComparison
,
cte_Premium
as
(
select [YearNum] as [YearNum], [January], [February],[March], [April],[May],[June],[July], [August], [September],[October],[November],[December] from ( select * from cte_Calendar) src
PIVOT
(
sum(src.Premium)
FOR src.[MonthName] IN ([January], [February],[March], [April],[May],[June],[July], [August], [September],[October],[November],[December])
) as [PivotTable]
--ORDER BY [YearNum] DESC
)
Select Cast(upyear.[YearNum] as varchar) + ' vs ' + Cast(downyear.[YearNum] as varchar) + ' % Change' [YearNum],
(upyear.January/downyear.January - 1) January, (upyear.February/downyear.February - 1) February,
(upyear.March/downyear.March - 1) March,
(upyear.April/downyear.April - 1) April,
(upyear.May/downyear.May - 1) May,
(upyear.June/downyear.June - 1) June,
(upyear.July/downyear.July - 1) July,
(upyear.August/downyear.August - 1) August,
(upyear.September/downyear.September - 1) September,
(upyear.October/downyear.October - 1) October,
(upyear.November/downyear.November - 1) November,
(upyear.December/downyear.December - 1) December
from cte_Premium upyear inner join cte_Premium downyear
ON upyear.[YearNum]=downyear.[YearNum] +1
order by [YearNum] DESC