我有一個名爲rain_tanks一個Postgres表更新,如下圖所示:選擇並在Postgres數據庫條件計算
id hour rain demand current_volume unmet_demand
1 00:00 4.0 2.0 2 0.0
2 00:10 3.0 4.0 [null] [null]
3 00:20 1.0 6.0 [null] [null]
4 00:30 7.0 3.0 [null] [null]
我想做到這一點的計算和更新current_volume和unmet_demand列(此代碼只是爲了。顯示需要做什麼,我想做到這一點,而無需使用Python中的函數或代碼行):
a = lag(current_volume) + rain - demand
if a < 0:
unmet_demand = current_volume
current_volume = 0
else:
unmet_demand = 0
current_volume = a
預計表:
id hour rain demand current_volume unmet_demand
1 00:00 4.0 2.0 2 0
2 00:10 3.0 4.0 1 0
3 00:20 1.0 6.0 0 -4
4 00:30 7.0 3.0 4 0
我想我需要的是先選擇和更新列。我嘗試了以下的選擇,但它不工作:
import psycopg2 as p
conn = p.connect("dbname = 'test' user = 'postgres' password = 'pass' host = 'localhost'")
cur = conn.cursor()
cur.execute("""SELECT Id,rain,demand,current_volume,unmet_demand,
CASE WHEN (rain - demand + lag(current_volume) over(
order by Id)) >= 0
THEN (rain - demand + lag(current_volume) over(
order by Id)) ELSE 0 END
FROM rain_tanks ORDER BY Id""")
任何幫助將非常感激。
編輯(添加與性能相關的問題):我決定在postgres數據庫中執行這些計算的原因是爲了查看在Python中使用numpy數組是否有速度改進。我有大約1000萬點的降雨和需求列,這裏提供的答案需要花費比雨天和需求數量龐大的等效python函數更長的時間。是否仍有空間來提高查詢的性能?
*不工作*是什麼意思? –
它不給我正確的結果。 –
所以你有第一行這些值..並希望得到它的其他人? –