SQL 代码对比:计算 2021 年 10 月订单平均交易金额和成本
这两段代码实现的功能相同,都是计算 2021 年 10 月份的订单平均交易金额和平均成本。不同之处在于第一段代码使用了折扣金额的计算,并且在子查询中使用了窗口函数来计算每个订单涉及的商品总价,而第二段代码直接在子查询中计算了每个订单的总价,没有使用窗口函数。另外,第一段代码中使用了 abs 函数计算折扣金额的绝对值,而第二段代码没有使用。
第一段代码:
select round(sum(total_amount)/count(*),1) as avg_amount,
round(sum(sum_price-total_amount)/count(*),1) as avg_cost
from
(select o.uid,
row_number()over(partition by uid order by event_time asc) as r,
sum(d.price*d.cnt) over(partition by o.order_id) as sum_price,
#sum_price是该订单各商品单价×数量之和,理论交易价格
#为啥这里要sum呢,因为tb_order_detail表里,一个order_id,可能涉及了多个物品
#因此join之后的大表,每一行都得显示这个总价格才行,不然和tb_order_overall里的total_amount没法相减
total_amount, #没折扣的交易金额
abs(d.price*d.cnt - total_amount) as discount_value, #折扣金额
o.event_time
from tb_product_info as i
join tb_order_detail as d on i.product_id = d.product_id
join tb_order_overall as o on o.order_id = d.order_id
where status = 1
) as t1
where r = 1
and year(event_time) = 2021
and month(event_time) = 10
#筛选日期为2021年10月
第二段代码:
select
round(sum(total_amount)/count(*),1),
round(sum((price-total_amount))/count(*),1)
from
(select
o.uid,
o.order_id,
o.total_amount,
sum(price*cnt)over(partition by o.uid) as price,
row_number()over(partition by uid order by event_time asc) as r,
o.event_time
from tb_product_info as i
join tb_order_detail as d on i.product_id = d.product_id
join tb_order_overall as o on o.order_id = d.order_id
where status = 1
) as t1
where r = 1
and year(event_time) = 2021
and month(event_time) = 10
总结:
第一段代码更详细地考虑了折扣因素,使用了窗口函数计算每个订单的商品总价,并且使用 abs 函数计算了折扣金额的绝对值。第二段代码则更简洁,直接计算了每个订单的总价,没有使用窗口函数和 abs 函数。选择哪段代码取决于具体的需求和数据情况。
原文地址: https://www.cveoy.top/t/topic/oyLN 著作权归作者所有。请勿转载和采集!