子查询的总和?

时间:2015-01-19 20:51:15

标签: sql sql-server

背景:

我们正在对数据库进行价格调整。价格调整基于材料清单以及每种材料的新成本。因此,我必须从项目表,物料清单和新价格表中选择项目,并根据制作每个项目所需的物料总数调整价格。项目由不同数量的不同材料组成,因此主查询将调用此子查询以获得总调整:

select
 ta.Code, 
 ta.Quantity,
 (select tb.cost - tb.NewCost * ta.Quantity ) as BOMEffect 

from BOM TA 
inner join ITEM TC on tC.ItemCode = tA.Father 
inner join NewPriceTable TB on tA.Code = tB.Item 


where TA.Father = '100-01'
and tc.PriceList = 3
order by ta.Father 

这给了我结果(这是一个项目的所有材料,每种材料的数量和价格调整):

Code    Quantity    BOMEffect
D .003  56.000000   -95.08
D .004  28.000000   -62
D .005  20.000000   -54.6
d .006  2.000000    -3.3
D .01   2.000000    -5.5
D .015  4.000000    -25.52
D .02   4.000000    -34

此查询所需的全部是BOMEffect(-280)。但是如果我只用以下代码替换select语句:

select
 sum((select tb.cost - tb.NewCost * ta.Quantity )) as BOMEffect 

from BOM TA 
inner join ITEM TC on tC.ItemCode = tA.Father 
inner join NewPriceTable TB on tA.Code = tB.Item 


where TA.Father = '100-01'
and tc.PriceList = 3
order by ta.Father 

我明白了:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

我知道它在说什么,但我不知道有什么其他方法可以做到。我怎么能得到这个总数?这是一个小的子查询,是更大查询的一部分,所以我只需要返回总数。我可以使用视图或临时表,但如果可能的话,我想远离它。

2 个答案:

答案 0 :(得分:1)

删除总和中的选择order by

select
sum(tb.cost - tb.NewCost * ta.Quantity) as BOMEffect 
from BOM TA 
inner join ITEM TC on tC.ItemCode = tA.Father 
inner join NewPriceTable TB on tA.Code = tB.Item 
where TA.Father = '100-01'
and tc.PriceList = 3

答案 1 :(得分:0)

如果要包含代码和数量,则必须在GROUP BY子句中包含这些内容:

select
ta.Code, 
 ta.Quantity,
sum(tb.cost - tb.NewCost * ta.Quantity) as BOMEffect 
from BOM TA 
inner join ITEM TC on tC.ItemCode = tA.Father 
inner join NewPriceTable TB on tA.Code = tB.Item 
where TA.Father = '100-01'
and tc.PriceList = 3
GROUP BY ta.Code, ta.Quantity