SQL 在排序列中查找第一个大于 X 的值

问题描述 投票:0回答:1

给定一个这样的表

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%)
sql postgresql aggregate-functions window-functions
1个回答
3
投票

使用窗函数

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)
© www.soinside.com 2019 - 2024. All rights reserved.