我有一個包含這些列的表:
id (int)
col1 (int)
col2 (varchar)
date1 (date)
col3 (int)
cumulative_col3 (int)
和大約 750k 行。
我想用相同日期和之前日期cumulative_col3的總和來更新.col3col1, col2date1
我在(date1),(date1, col1, col2)和上有索引(col1, col2)。
我嘗試了以下查詢,但需要很長時間才能完成。
update table_name
set cumulative_col3 = (select sum(s.col3)
from table_name s
where s.date1 <= table_name.date1
and s.col1 = table_name.col1
and s.col2 = table_name.col2);
我可以做些什么來提高這個查詢的性能?
uj5u.com熱心網友回復:
您可以嘗試在派生表中計算運行總和:
update table_name
set cumulative_col3 = t.cum_sum
from (
select id,
sum(s.col3) over (partition by col1, col2 order by date1) as cum_sum
from table_name
) s
where s.id = table_name.id;
這假定這id是表的主鍵。
uj5u.com熱心網友回復:
您可以嘗試將以下索引添加到您的表中:
CREATE INDEX idx ON table_name (date1, col1, col2, col3);
如果使用此索引,則應允許更快地評估相關總和子查詢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/514697.html
上一篇:在范圍內插入id
下一篇:特定事件后的SQL過濾活動
