我正在嘗試按組和總計向表中添加小計。我使用下面的示例重新創建了數據。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
我需要添加的客戶分類彙總僅低於客戶的出現和總表的最後一行是這樣的:
什麼我已經嘗試了至今:
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),
哪有我在上面提供的表格中添加了小計和總數?
我打開使用沒有ROLLUP運算符的查詢。我認爲可以使用工會但不知道如何開始。
感謝您考慮我的問題。
它的工作原理,用224行測試,花費的時間比'時間少UNION'解決方案由@GiorgiosBetsos提出。非常感謝! –