SQL SERVER T-SQL 按组计算小计和总计

SQL SERVER T-SQL Calculate SubTotal and Total by group

我正在尝试按组和总计添加小计到 table。我使用以下示例重新创建了数据。

DECLARE @Sales TABLE(
        CustomerName  VARCHAR(20),
        LegalID VARCHAR(20),
        Employee VARCHAR(20),
        DocDate DATE,
        DocTotal Int,
        DueTotal Int
)
INSERT INTO @Sales SELECT 'Jhon Titor','12345', 'Employee1','2015-09-01',1000,200 
INSERT INTO @Sales SELECT 'Jhon Titor','12345', 'Employee1','2015-08-20',500,100
INSERT INTO @Sales SELECT 'Jhon Titor','12345', 'Employee1','2015-08-18',200,50 
INSERT INTO @Sales SELECT 'Deli Armstrong','2345', 'Employee1','2015-09-17',2300,700
INSERT INTO @Sales SELECT 'Deli Armstrong','2345', 'Employee1','2015-09-11',5000,1000
INSERT INTO @Sales SELECT 'Ali Mezzu','6789', 'Employee1','2015-09-07',300,200

选择@Sales

我需要在 table 的最后一行的客户出现次数和总计下方添加客户小计,如下所示:

到目前为止我尝试过的:

select 
    case 
        when GROUPING(CustomerName) = 1 and
             GROUPING(Employee) = 1 and 
             GROUPING(DocDate) = 1 and
             GROUPING(LegalID) = 0 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 LegalID, CustomerName,Employee,DocDate with rollup

但是我得到的小计为 null,它应该说 Total Jhon Titor 因为我在查询中将它设置为静态,而且它对每个未聚合的列 (3)、

重复

如何将小计和总计添加到上面显示的 table?

我愿意使用不带 ROLLUP 运算符的查询。我认为可以使用联合,但不知道如何开始。

感谢您考虑我的问题。

您可以使用以下查询:

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

我想这就是你想要的:

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