2015-09-30 115 views
0

我有以下查詢,它的工作原理。 我只需要在給出的總計在SQL中添加總計到總數

SELECT ItemType.Description, 
     SUM(Price * Quantity)as 'TOTAL' 
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine] 
join Item 
    on PurchaseOrderReceivingLine.ItemFK = item.ItemPK 
join ItemType 
    on Item.ItemTypeFK = ItemType.ItemTypePK 
join PurchaseOrderReceiving 
    on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK 
where InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) 
    and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0) 
group by ItemType.Description 
+1

爲什麼你不計算任何報表工具/代碼總計您使用呈現數據? –

+0

你可以把你的查詢結果放在一個臨時表中,然後在你的臨時表中放入一個總數。然後,你只需將它們與你的總數聯合在一起。 – PeonProgrammer

回答

1

使用CTEUNION與總計行的行底部添加一行。

with CTE 
(
    SELECT ItemType.Description, 
     SUM(Price * Quantity)as 'TOTAL' 
     FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine] 
    join Item on PurchaseOrderReceivingLine.ItemFK = item.ItemPK 
    join ItemType on Item.ItemTypeFK = ItemType.ItemTypePK 
    join PurchaseOrderReceiving on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK 
    where 
    InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) 
    and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0) 
    group by ItemType.Description 
) 

SELECT Description,TOTAL FROM CTE 
UNION 
SELECT 'GRAND TOTAL',SUM(TOTAL) FROM CTE 
0

使用您的返回結果作爲臨時結果

;WITH TEMP AS(
SELECT ItemType.Description, SUM(Price * Quantity)as 'TOTAL' 
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine] 
join Item 
    on PurchaseOrderReceivingLine.ItemFK = item.ItemPK 
join ItemType 
    on Item.ItemTypeFK = ItemType.ItemTypePK 
join PurchaseOrderReceiving 
    on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK 
where InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) 
    and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0) 
group by ItemType.Description 
) 
SELECT * FROM TEMP 
UNION 
SELECT 'BIG SUM',SUM(TOTAL) TEMP