How to get a total sum for each Description and order it in dynamic pivot

230 Views Asked by At

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:

enter image description here

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:

enter image description here

UPDATE: using GROUPING SETS

enter image description here UPDATE: This is how data looks before PIVOT:

enter image description here

1

There are 1 best solutions below

4
On BEST ANSWER

What about this:

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,'') + ',' + '[Total]'
--print @cols

SELECT @query = 
'
        ;with cte_TopClasses
AS  ( 
        SELECT      
                    ISNULL(CAST(b.MonthNum as varchar(2)) + ''/''+ CAST(b.YearNum as varchar(4)), ''Total'') 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    GROUPING SETS
        (
                (
                    b.YearNum ,
                    b.MonthNum, 
                    GovClassCode,   
                    dda.GovClassDesc
                )
                , 
                (
                    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

The idea is to add the Total column in T-SQL using GROUPING SETS