2015-09-25 183 views
2

我正在尝试按组和总计向表中添加小计。我使用下面的示例重新创建了数据。SQL SERVER T-SQL按组计算小计总计和总计

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

enter image description here

我需要添加的客户分类汇总仅低于客户的出现和总表的最后一行是这样的:

enter image description here

什么我已经尝试了至今:

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 

但我正在逐渐大部为空,它应该说Total Jhon Titor因为我把它在查询静态的,也被重复每一个未聚集列(3),

enter image description here

哪有我在上面提供的表格中添加了小计和总数?

我打开使用没有ROLLUP运算符的查询。我认为可以使用工会但不知道如何开始。

感谢您考虑我的问题。

回答

3

我想这是你想要的东西:

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

它的工作原理,用224行测试,花费的时间比'时间少UNION'解决方案由@GiorgiosBetsos提出。非常感谢! –

1

您可以使用下面的查询:

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