给定一个这样的表
id total_cost margin
a 2 10%
b 4 15%
c 6 4%
x 7 90%
y 8 13%
z 9 0%
总成本被定义为某个正列的运行聚合,因此它始终是排序的。 我需要在单个 SQL 命令中找出成本首先超过或等于数字 X 的平均利润率(需要高效)。
即给定 X = 7.5
我需要找到total_cost首先超过或等于7.5的平均利润。在这种情况下,条件将应用于自
起的前 5 列id total_cost margin
y 8 13%
是total_cost超过7.5的第一列。结果就是
avg(10%, 15%, 4%, 90%, 13%)
使用窗函数
lag()
:
select id, total_cost, margin
from (
select *, lag(total_cost) over (order by total_cost) prev_total_cost
from the_table
) s
where coalesce(prev_total_cost, 0) < 7.5
id | total_cost | margin
----+------------+--------
a | 2 | 0.10
b | 4 | 0.15
c | 6 | 0.04
x | 7 | 0.90
y | 8 | 0.13
(5 rows)
获取平均值:
select avg(margin)
from (
select *, lag(total_cost) over (order by total_cost) prev_total_cost
from the_table
) s
where coalesce(prev_total_cost, 0) < 7.5
avg
------------------------
0.26400000000000000000
(1 row)