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

ale*_*eta 5 sql t-sql sql-server rollup subtotal

我试图按组和总计添加小计到表.我使用以下示例重新创建了数据.

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
Run Code Online (Sandbox Code Playgroud)

选择 @Sales

在此输入图像描述

我需要在客户事件的下方添加客户小计,并在表的最后一行添加总计,如下所示:

在此输入图像描述

到目前为止我尝试过的:

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
Run Code Online (Sandbox Code Playgroud)

但是Total Jhon Titor当我在查询中将其设置为静态时,我得到小计为null,它也会在每个未聚合的列(3)中重复,

在此输入图像描述

如何在上面的表格中添加小计和总计?

我愿意使用没有ROLLUP运算符的查询.我认为使用工会是可能的,但不知道如何开始.

谢谢你考虑我的问题.

Gor*_*off 8

我想这就是你想要的:

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),
                       ()
                      );
Run Code Online (Sandbox Code Playgroud)