sql - 使用 sql 查询获取总折扣
问题描述
我有一个查询来计算每件商品的折扣。现在我想要的是得到总的折扣。我怎样才能做到这一点?
我计算折扣的查询是:
select (dla.unit_list_price + dla.unit_selling_price) * dla.ordered_qty as discount
, dla.itemname as item_name
from doo_lines_all dla
例如,下面是我做的查询的返回数据。
Item_Name Discount
Item1 50
Item2 25
Item3 30
现在我想要的是获得我预期结果的总折扣105
解决方案
您必须放弃项目名称:
select sum((dla.unit_list_price + dla.unit_selling_price) * dla.ordered_qty) as totaldiscount
from doo_lines_all dla
这将只产生一个“105”的输出(一行,一列)
如果您想保留项目名称并让行显示单个折扣和重复总数,我们可以使用分析:
select
dla.itemname,
(dla.unit_list_price + dla.unit_selling_price) * dla.ordered_qty as discount,
sum((dla.unit_list_price + dla.unit_selling_price) * dla.ordered_qty) over() as totaldiscount
from doo_lines_all dla
这将产生如下输出:
Item_Name Discount TotalDiscount
Item1 50 105
Item2 25 105
Item3 30 105
还有其他方法可以实现相同的目标,但分析函数可能是最简单的编写方法,尽管可能比这样做更难理解:
select
dla.itemname,
(dla.unit_list_price + dla.unit_selling_price) * dla.ordered_qty as discount,
t.totaldiscount
from doo_lines_all dla
cross join
(
select sum((unit_list_price + unit_selling_price) * ordered_qty) as totaldiscount
from doo_lines_all
) t
这计算出子查询中的总数,然后通过交叉连接将其连接到 dla 中的每一行。您可以认为它与分析的工作方式相同/这是思考分析如何工作的一种方式
推荐阅读
- api - 通过浏览器访问 idx-analytics-data-api
- javascript - jquery resizable 1px不匹配错误
- python - 如何在 Spyder (Anaconda) 中找到当前 .py 文件的路径?
- tensorflow - parameterServerType 和 workerCount 之间的比率/关系应该是什么?
- android - CheckBox 状态保存不起作用
- excel - 在 Excel 中选择最小值和对应的列
- javascript - 使用 jquery 在 django 上进行 Panzoom
- cmd - 从 TeamCity 运行 TF.exe 失败。来自同一服务器的相同脚本并使用相同的用户作为代理成功
- amazon-web-services - AWS IAM 访问除修改管理员用户之外的所有内容
- javascript - Javascript 使用异步加载本地 .txt 文件