在SQL中将总计添加到总计中

时间:2015-09-30 13:29:05

标签: sql-server-2008

我有下面的查询,它有效。 我只需要在底部添加一行代表总计

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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