首页 > 解决方案 > 用别名求和列?

问题描述

我正在尝试对具有别名的列求和(因为要创建列,我必须对其他列进行数学运算)。我知道您不能这样做(在同一选择查询中创建的别名上的聚合函数),但我搜索的解决方案似乎都不适合我。

这是我的代码

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.

我不完全理解。

标签: sqlsql-server

解决方案


如果要使用 sum 保留现有值,则需要使用OVER子句 with 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 

推荐阅读