SQL SERVER T-SQL Calculate SubTotal and Total by group

前端 未结 2 1979
暖寄归人
暖寄归人 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: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),
                           ()
                          );
    

提交回复
热议问题