select 基于商店的每个产品的最新余额 (SQL)
select the latest balance for each product based on store (SQL)
我正在尝试根据 storeid 获取每个产品的最新余额。但我不知道为什么会得到重复的股票名称 sasi
.
Sql查询
select stockname, balance,updatedat,storename,s1.productid,s1.storeid
from stockmovement s1
inner join (select storeid, productid, max(updatedat) as maxdate
from stockmovement
group by storeid,productid) s2
on s2.storeid = s1.storeid and s2.maxdate = s1.updatedat
使用 row_number() 尝试以下查询:
select stockname, balance, bupdatedat, storename,productid,storeid from
(
select stockname, balance, bupdatedat, storename,productid,storeid, row_number() over
(partition by storeid,productid order by bupdatedat date desc) rn
)t where rn=1
select stockname, balance, updatedat, storename,productid,storeid from
(
select stockname, balance, updatedat, storename,productid,storeid, row_number() over
(partition by storeid,productid order by updatedat desc )rn from stockmovement
)t where rn=1
这是 Postgres 中的 greatest-n-per-group problem, and they can be solved efficiently using distinct on ()
:
select distinct on (storeid, productid) *
from stockmovement
order by storeid, productid, updatedat desc
这通常比使用 window 函数的等效解决方案更快。
我正在尝试根据 storeid 获取每个产品的最新余额。但我不知道为什么会得到重复的股票名称 sasi
.
Sql查询
select stockname, balance,updatedat,storename,s1.productid,s1.storeid
from stockmovement s1
inner join (select storeid, productid, max(updatedat) as maxdate
from stockmovement
group by storeid,productid) s2
on s2.storeid = s1.storeid and s2.maxdate = s1.updatedat
使用 row_number() 尝试以下查询:
select stockname, balance, bupdatedat, storename,productid,storeid from
(
select stockname, balance, bupdatedat, storename,productid,storeid, row_number() over
(partition by storeid,productid order by bupdatedat date desc) rn
)t where rn=1
select stockname, balance, updatedat, storename,productid,storeid from
(
select stockname, balance, updatedat, storename,productid,storeid, row_number() over
(partition by storeid,productid order by updatedat desc )rn from stockmovement
)t where rn=1
这是 Postgres 中的 greatest-n-per-group problem, and they can be solved efficiently using distinct on ()
:
select distinct on (storeid, productid) *
from stockmovement
order by storeid, productid, updatedat desc
这通常比使用 window 函数的等效解决方案更快。