1
SELECT distinct on (prices.item_id) *
FROM prices
ORDER BY prices.item_id, prices.updated_at DESC

上面的查询检索最近的价格,我如何获得所有当前价格的总和?

是否可以不使用子选择?

4

1 回答 1

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。

于 2012-09-13T17:51:17.777 回答