SQL SERVER T-SQL Calculate SubTotal and Total by group

前端 未结 2 1959
暖寄归人
暖寄归人 2021-01-12 09:33

I am trying to add subtotal by group and total to a table. I\'ve recreated the data using the following sample.

DECLARE @Sales TABLE(
        CustomerName  VA         


        
相关标签:
2条回答
  • 2021-01-12 10:06

    You can use the following query:

    SELECT CustomerName, LegalID, Employee, DocDate, DocTotal, DueTotal
    FROM (       
      SELECT CustomerName AS cName, CustomerName, 
             LegalID, Employee, DocDate, DocTotal, DueTotal,
             1 AS ord
      FROM Sales
    
      UNION ALL
    
      SELECT CustomerName AS cName, CONCAT('Total ', CustomerName), 
             NULL, NULL, NULL, 
             SUM(DocTotal), SUM(DueTotal), 2 AS ord
      FROM Sales
      GROUP BY CustomerName
    
      UNION ALL 
    
      SELECT 'ZZZZ' AS cName, 'Total', NULL, NULL, NULL, 
             SUM(DocTotal), SUM(DueTotal), 3 AS ord
      FROM Sales ) AS t
    ORDER BY cName, ord
    

    Demo here

    0 讨论(0)
  • 2021-01-12 10:19

    I think this is what you want:

    select (case when GROUPING(CustomerName) = 0 and
                      GROUPING(Employee) = 1 and 
                      GROUPING(DocDate) = 1 and
                      GROUPING(LegalID) = 1
                 then 'Total ' + CustomerName
                 when GROUPING(CustomerName) = 1 and
                      GROUPING(Employee) = 1 and
                      GROUPING(DocDate) =1 and
                      GROUPING(LegalID) = 1 then 'Total'
                 else CustomerName
            end) as CustomerName,
           LegalID, Employee,DocDate,
           sum(DocTotal) as DocTotal,
           sum(DueTotal) as DueTotal 
    From @Sales 
    group by grouping sets((LegalID, CustomerName ,Employee, DocDate),
                           (CustomerName),
                           ()
                          );
    
    0 讨论(0)
提交回复
热议问题