2016-12-15 38 views
0

給定一個表像這樣SQL找到第一個值大於X的排序列

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。在這種情況下的條件會因爲

id  total_cost margin 
y  8   13% 

被施加到第一列5是其中TOTAL_COST超過7.5的第一列。其結果將是

avg(10%, 15%, 4%, 90%, 13%) 
+0

'所以它總是sorted' ...有沒有在內部秩序一個Postgres表格,只有你施加的訂單。我們可以假設總成本隨着id增加而增加嗎? –

+0

你有關於你在找什麼的相互矛盾的陳述。 –

+0

更不用說當你說「這裏是前5列」時它意味着什麼。什麼。我不知道你甚至在問什麼。 –

回答

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) 
相關問題