![](/img/trans.png)
[英]How do I compare column values between two rows which share the same value of another column?
[英]SQLite: How can I update a column with a value that is the difference between two rows of another column?
如何更新具有與另一列兩行之間的差異(百分比)的值的列?
從:
y | coeff | decreased %
---|-------|------------
15 | 1.35 |
16 | 1.22 |
17 | 1.14 |
18 | 1 |
至:
y | coeff | decreased %
---|-------|------------
15 | 1.35 |
16 | 1.22 | 9.629
17 | 1.14 | 6.557
18 | 1 | 12.280
使用此UPDATE
可以獲取coeff
的先前值,即使id不是連續的:
update tablename
set decreased = 100.0 * (1.0 - coeff / (
select t.coeff from tablename t
where t.y = (select max(p.y) from tablename p where p.y < tablename.y)
)
)
觀看演示
我會這樣:
update tbl a
set dec_p = select (a.coeff-b.coeff)/a.coeff as dec
from a left join tbl b on (a.y=b.y+1)
如果您的y
確實是連續無間隙的,則使用left join
:
select t.*, 100 - (t.coeff * 100.0 / tprev.coeff) as decreased
from t left join
t tprev
on tprev.y = t.y - 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.