SELECT distinct on (prices.item_id) *
FROM prices
ORDER BY prices.item_id, prices.updated_at DESC
以上查询检索最近的价格,我如何得到所有当前价格的总和?
是否可以不使用子选择?
答案 0 :(得分:2)
使用子查询这是微不足道的:
select sum(p.price)
from (select distinct on (p.item_id) p.*
from prices p
order by p.item_id, p.updated_at desc
) p
如果您不介意重复行,我认为以下内容可能会有效:
select distinct on (p.item_id) sum(prices.price) over ()
from prices p
order by p.item_id, p.updated_at desc
您可以为此添加限制条款以获得所需内容。顺便说一下,我会把它写成:
select sum(p.price)
from (select p.*,
row_number() over (partition by p.item_id order by updated_at desc) as seqnum
from prices p
order by p.item_id, p.updated_at desc
) p
where seqnum = 1
ROW_NUMBER()是标准SQL。 DISTINCT ON子句特定于Postgres。