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

上面的查询检索最近的价格,我如何得到所有当前价格的总和?
不使用子选择是否可行?

最佳答案

使用子查询很简单:

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

行数()是标准SQL。DISTINCT ON子句是Postgres特有的。

关于sql - 汇总最近的行(按ID分组),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12411773/

10-11 01:21