2015-09-25 187 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