sql - 用别名求和列?
问题描述
我正在尝试对具有别名的列求和(因为要创建列,我必须对其他列进行数学运算)。我知道您不能这样做(在同一选择查询中创建的别名上的聚合函数),但我搜索的解决方案似乎都不适合我。
这是我的代码
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.
我不完全理解。
解决方案
如果要使用 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
推荐阅读
- google-apps-script - getValue() 不从源文件中返回数据,Google App Script
- javascript - 用 Applescript 在线替换文本
- kubernetes - Kubernetes 网络插件
- php - php排序多嵌套数组
- codeigniter - codeigniter form_error() 在表单控件旁边没有显示错误
- git - vscode-sftp 扩展与 Git 跟踪冲突
- postgresql - Dockerfile ENV 变量不被接受
- c++ - volatile、const、volatile const 和“nether”类型之间的转换
- javascript - 在初始页面加载 Mixitup 时显示过滤项目的计数
- javascript - 为什么我不能直接在 SetTimeout 函数中为 Promises 调用 resolve()