Postgresql 用累计和更新列
Postgresql update a column with cumulative sum
我有一个table'company_abc'。它有 2 个主键(id,年),第 3 列是数值,第 4 列应该填充每年第 3 列值的累计和。我尝试了以下方法:
update company_abc
set srti = ww.srti
from (SELECT sum(company_abc.salestotal) over (partition by year order by salestotal desc) as stri) ww;
也尝试过:
update company_abc
set (cid, year, srti) = (SELECT company_abc.cid, company_abc.year, sum(company_abc.salestotal) over (partition by year order by salestotal DESC)
FROM company_abc
ORDER BY year desc);
在这两种情况下,它都失败了。
你似乎想要一个 update
和自我 join
:
update company_abc c
set stri = c1.stri
from (
select id, year,
sum(salestotal) over(partition by year order by salestotal desc) stri
from company_abc
) c1
where c1.id = c.year and c1.id = c.id
子查询计算 window 总和(使用与原始代码中相同的表达式),然后我们使用 table 的主键更新相应行上的值table.
我有一个table'company_abc'。它有 2 个主键(id,年),第 3 列是数值,第 4 列应该填充每年第 3 列值的累计和。我尝试了以下方法:
update company_abc
set srti = ww.srti
from (SELECT sum(company_abc.salestotal) over (partition by year order by salestotal desc) as stri) ww;
也尝试过:
update company_abc
set (cid, year, srti) = (SELECT company_abc.cid, company_abc.year, sum(company_abc.salestotal) over (partition by year order by salestotal DESC)
FROM company_abc
ORDER BY year desc);
在这两种情况下,它都失败了。
你似乎想要一个 update
和自我 join
:
update company_abc c
set stri = c1.stri
from (
select id, year,
sum(salestotal) over(partition by year order by salestotal desc) stri
from company_abc
) c1
where c1.id = c.year and c1.id = c.id
子查询计算 window 总和(使用与原始代码中相同的表达式),然后我们使用 table 的主键更新相应行上的值table.