I need to display only top 10 rows based on total sum
for each Class
and order it by Total sum desc.
This is what I am trying to achieve:
So I have my dynamic pivot but I cant understand how to get total
column for each row and then display only top 10 by Total
column.
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = STUFF(
(SELECT distinct ',' + QUOTENAME([YearMonth])
FROM #MyTable
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
--print @cols
SELECT @query =
'
;with cte_TopClasses
AS (
SELECT
CAST(b.MonthNum as varchar(2)) + ''/''+ CAST(b.YearNum as varchar(4)) as YearMonth,
b.YearNum,
b.MonthNum,
GovClassCode + ''- '' + dda.GovClassDesc as Class,
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()) )
AND GovClassCode + '' - '' + dda.GovClassDesc IS NOT NULL
GROUP BY b.YearNum ,
b.MonthNum,
GovClassCode,
dda.GovClassDesc
)
SELECT * FROM
(SELECT
[YearMonth],
Class,
NetWrittenPremium
FROM cte_TopClasses)X
PIVOT
(
sum(NetWrittenPremium)
for [YearMonth] in (' + @cols + ')
) P
'
EXEC SP_EXECUTESQL @query
output from that is 73 rows:
UPDATE: using GROUPING SETS
What about this:
The idea is to add the
Total
column in T-SQL usingGROUPING SETS