我有一个数据集,其中我有一个ItemID,然后按每个价格出售数量:
ItemID | Quantity | Price
ABC 10 14.50
ABC 4 14.25
DEF 32 22.41
ABC 24 14.10
GHI 8 8.50
GHI 12 8.60
DEF 2 22.30
每个条目都有ItemID和Price的唯一组合。我想添加第四列,其中包含该ItemID的总销售量。所以上面的表格看起来像这样:
ItemID | Quantity | Price | TotalQ
ABC 10 14.50 38
ABC 4 14.25 38
DEF 32 22.41 34
ABC 24 14.10 38
GHI 8 8.50 20
GHI 12 8.60 20
DEF 2 22.30 34
如果不对聚合函数执行聚合函数,我似乎无法做到这一点,这显然会产生错误。我将如何完成这项工作?
我正在使用SQL Server 2008。
答案 0 :(得分:4)
请尝试:
SELECT
*,
SUM(Quantity) OVER(PARTITION BY ItemID) TotalQ
FROM
YourTable
答案 1 :(得分:0)
试试此代码
select a.ItemID,a.Quantity,a.Price,x.Total form table_name a
left outer join
(select sum(Quantity) Total, ItemID from table_name group by ItemID)x
on x.ItemID = a.ItemID
答案 2 :(得分:0)
如果你只是在查询中需要这个,你可以这样写:
;WITH CTE_Total AS
(
SELECT ItemID, SUM(Quantity) as TotalQ
FROM YourTable
GROUP BY ItemID
)
SELECT t.*, c.TotalQ
FROM YourTable t
LEFT JOIN CTE_Total c on t.ItemID = c.ItemID
<强> SQLFiddle DEMO 强>
但是,如果您想在表中使用自动计算列,首先需要创建执行计算的函数:
CREATE FUNCTION dbo.fn_YourTableTotalQ (@ItemID VARCHAR(3))
RETURNS Int
AS
BEGIN
DECLARE @toRet INT
SELECT @toRet = COALESCE(SUM(Quantity),0)
FROM YourTable WHERE ItemID = @ItemID
RETURN @toRet
END
...然后使用此函数添加新列:
ALTER TABLE YourTable
ADD TotalQ AS dbo.fn_YourTableTotalQ(ItemID)
<强> SQLFiddle DEMO 强>