首页 > 解决方案 > 使用 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

标签: sqloracle

解决方案


您必须放弃项目名称:

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 中的每一行。您可以认为它与分析的工作方式相同/这是思考分析如何工作的一种方式


推荐阅读