2017-05-31 71 views
1

我有以下數據的表:計算列:當前滯後計算超過PostgreSQL中

| id | Date (dd/mm/yyyy) | Factor | Actual | Current | 
|----|-------------------|--------|--------|----------| 
| 1 |  04/01/2017 | 0.5 | 100 | 100  | 
| 2 |  04/02/2017 | 0.5 | 120 | 100  | 
| 3 |  04/03/2017 | 0.5 | 120 | 110  | 
| 4 |  04/04/2017 | 0.5 | 115 | 115  | 
| 5 |  04/05/2017 | 0.5 | 125 | 115  | 
| 6 |  04/06/2017 | 0.5 | 100 | 120  | 
| 7 |  04/07/2017 | 0.5 | 100 | 110  | 

當前行=前一行+因子*(實際前一行的 - 前一行的電流)的電流

For id = 1, current = same as actual = 100 
    For id = 2, current = 100 + 0.5 * (100 - 100) = 100 
    For id = 3, current = 100 + 0.5 * (120 - 100) = 110 
    For id = 4, current = 110 + 0.5 * (120 - 110) = 115 
and so on... 

如何在postgresql中使用查詢來實現?

+0

請詳細說明後 - 不清楚什麼你,你怎麼想 –

+1

你的計算顯示120作爲'ID實際值= 4',但高於該表顯示115,你能否詳細說明這或修復它? –

+0

@LaurenzAlbe - 對於'id = 4',從第3行得到'actual'('actual'和'current'來自前一行)。 – klin

回答

1

您需要遞歸查詢。

with recursive my_table_with_rn as 
(
    select *, row_number() over (order by id) as rn 
    from my_table 
), 

rec_query(rn, id, date, factor, actual, current) as 
(
    select rn, id, date, factor, actual, actual 
    from my_table_with_rn 
    where rn = 1 

union all 

    select 
     t.rn, t.id, t.date, t.factor, t.actual, 
     p.current + t.factor * (p.actual - p.current) 
    from rec_query p 
    join my_table_with_rn t on t.rn = p.rn + 1 
) 

select id, date, factor, actual, current 
from rec_query 
order by id; 

注意,這row_number()加入的情況下工作的時候ids是不連續的(這不是必需的實際數據,你可以使用id代替rn)。

Test it here.

+0

Thx @klin查詢 – Alice