SELECT distinct on (prices.item_id) *
FROM prices
ORDER BY prices.item_id, prices.updated_at DESC
上記のクエリは最新の価格を取得しますが、現在のすべての価格の合計を取得するにはどうすればよいでしょうか?
サブセレクトを使わなくても可能ですか?
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
ROW_NUMBER() は標準 SQL です。DISTINCT ON 句は Postgres に固有です。