总和列的别名?

时间:2018-12-28 19:08:49

标签: sql sql-server

我正在尝试对一个具有别名的列求和(因为要创建该列,我必须对其他列进行数学运算)。我知道您无法执行此操作(在同一选择查询中创建的别名上的聚合函数),但是我搜索过的所有解决方案似乎都不适合我。

这是我的代码

Select 
o.Order_Value Total_Price_Before_Discount, 
od.Price*od.Quantity_Ordered as Line_Price_Before_Discount, 
od.Discount_Value, od.Discount_Percentage, 
od.Price*od.Quantity_Ordered-od.Discount_Value as Line_Price_After_Discount,

sum(Line_Price_After_Discount) as Total_Price_After_Discount, -- this is the problem line

from Orders o (nolock)
join Order_Detail od (nolock) on 
o.Company_Code=od.Company_Code and o.Division_Code=od.Division_Code 

我尝试了

sum(od.Price*od.Quantity_Ordered-od.Discount_Value) as Total_Price_After_Discount

但是那没有用,我被错误地分组了

 invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我不太了解。

2 个答案:

答案 0 :(得分:0)

如果要将现有值保留为sum,则需要对OVER使用PARTITION BY子句。如果您按照以下步骤更改脚本,则该脚本应该起作用。

此外,您确定您的加入正确吗? Company_Code和Division_Code对连接Order和Order_Detail表是奇怪的。

Select 
    o.Order_Value Total_Price_Before_Discount, 
    od.Price*od.Quantity_Ordered as Line_Price_Before_Discount, 
    od.Discount_Value, od.Discount_Percentage, 
    od.Price*od.Quantity_Ordered-od.Discount_Value as Line_Price_After_Discount,

    --sum(Line_Price_After_Discount) as Total_Price_After_Discount, -- this is the problem line
    SUM(od.Price*od.Quantity_Ordered-od.Discount_Value) OVER(PARTITION BY o.Company_Code,o.Division_Code) AS Total_Price_After_Discount

from Orders o (nolock)
join Order_Detail od (nolock) on o.Company_Code=od.Company_Code and o.Division_Code=od.Division_Code 

答案 1 :(得分:0)

一种快速的解决方法是将查询包装在CTE或子查询中,然后将聚合移出它

select 
    *,
    sum(Line_Price_After_Discount) as Total_Price_After_Discount
from(
    Select 
       o.Order_Value Total_Price_Before_Discount, 
       od.Price*od.Quantity_Ordered as Line_Price_Before_Discount, 
       od.Discount_Value, 
       od.Discount_Percentage, 
       od.Price*od.Quantity_Ordered-od.Discount_Value as Line_Price_After_Discount
    from Orders o (nolock)
    join Order_Detail od (nolock) on 
    o.Company_Code=od.Company_Code and o.Division_Code=od.Division_Code
    ) x
group by 
    Total_Price_Before_Discount,
    Line_Price_Before_Discount,
    Discount_Value,
    Discount_Percentage,
    Line_Price_After_Discount