SQL SERVER T-SQL Calculate SubTotal and Total by group

只愿长相守 提交于 2019-12-01 05:55:53

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),
                       ()
                      );

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!