I have a dynamic dataset that returns data from today and a year back.
How can I pivot this data and return only top 10 Description
by NetWrittenPremium
?
I know how to perform static pivot, but confused how would I do it in this case.
;with cte_TopClasses
AS (
SELECT
b.MonthNum,
b.YearNum,
GovClassCode + ' - ' + dda.GovClassDesc as Description,
ISNULL(SUM(Premium),0) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.YearNum = Year(prm.EffectiveDate) AND b.MonthNum=Month(prm.EffectiveDate) AND CompanyLine = 'Arch Insurance Company'
LEFT JOIN [dbo].[Dynamic_Data_ArchWC] dda ON prm.QuoteGUID = dda.QuoteGuid
WHERE
( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum ,
b.MonthNum,
GovClassCode,
dda.GovClassDesc
)
--here I want to pivot it
select *
from cte_TopClasses
Current result is 128 records.
And desirable result would be something like that:
@Nico It should be like that:
Yours is very close, just shift to 1 month ahead.
Maybe it's somewhat complicated. More information about dynamic pivot, you can check this post.