我一直在尝试“合并”两个查询以获取具有最新价格的产品的最后更新日期,但未成功。
看看这个:
我有2个不同的表:products_table和products_prices
在 products_table 中,我拥有所有不同的产品,并且每次更改属性时,字段last_update_date也会更改。
如果我想获取产品的最新更新,请使用以下查询:
select a.item,a.last_update_date from products_table a inner join
(Select item, max(last_update_date) updates from products_table
group by item) b
on a.item=b.item --item is the product_id
and a.last_update_date=b.updates
此外,我具有表 products_prices ,该表包含产品的所有不同价格,如果我想获取产品的最新价格,我将使用此查询(按request_id进行过滤):< / p>
select * from products_prices a
where item_code = ''--Product_id
and request_id = (select max(request_id) from products_prices b where a.item_code=b.item_code);
问题是我不知道如何合并这2个查询以获取同一行中产品的最新更新和最新价格
能请你帮我吗?
答案 0 :(得分:1)
Select first_query.last_update_date, second_query.latest_price -- or whatever name it is
from
(select a.item, a.last_update_date from products_table a inner join
(Select item, max(last_update_date) updates from products_table
group by item) b
on a.item=b.item --item is the product_id
and a.last_update_date=b.updates) first_query,
(select * from products_prices a
where item_code = ''--Product_id
and request_id = (select max(request_id) from products_prices b where a.item_code=b.item_code)) second_query
where
first_query.item = second_query.item_code;
答案 1 :(得分:0)
使用窗口功能会更简单:
select p.item, p.last_update_date, pp.*
from (select p.*,
row_number() over (partition by p.item order by p.last_update_date desc) as seqnum
from products_table p
) p join
(select pp.*,
row_number() over (partition by pp.item_code order by pp.request_id desc) as seqnum
from pp p
) pp
on pp.item_code = p.item
where p.seqnum = 1 and pp.seqnum = 1;