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

时间:2016-12-15 06:28:45

标签: sql postgresql

给出这样一个表

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%)

1 个答案:

答案 0 :(得分:0)

使用窗口函数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)
相关问题