在 group by 中使用正确的报价 ID 获取最高报价并加入查询
Get highest offer price with correct offer id in group by and join query
我正在使用产品 ID 加入产品 table 并提供报价 table,我的要求是获得该产品的最高报价 (%),同时我想按条款分组产品 ID,因为我不想重复产品,但它显示错误的报价 ID,因为首先根据产品 ID 执行加入查询:
产品table:
id name
1 abc
2 xyz
出价table
id to_date product_id offer
1 2020-12-18 1 30%
2 2020-12-18 1 40%
3 2020-12-18 2 30%
4 2020-12-18 2 40%
查询:
SELECT product_id,product.name,o.id as offer_id,o.to_date, max(o.offer)offer_price
FROM products
LEFT JOIN offers o ON o.product_id=product.id
GROUP BY product.id
有问题的输出(错误的报价 ID):
offer_id product_id to_date offer_price
1 1 2020-12-18 40%
3 2 2020-12-18 40%
预期输出(正确的报价 ID)
offer_id product_id to_date offer_price
2 1 2020-12-18 40%
4 2 2020-12-18 40%
您可以使用 window 函数:
select o.*, p.name as product_name
from product p
left join (
select o.*,
row_number() over(partition by product_id order by offer desc) rn
from offer o
) o on o.product_id = p.id and o.rn = 1
row_number()
通过降序 offer
对具有相同 product_id
的记录进行排名 - 因此每个产品报价最高的行获得排名 1
。然后您可以使用该信息进行过滤。
这需要 MySQL 8.0。在早期版本中,一种替代方法使用相关子查询来过滤每个产品的最大报价:
select o.*, p.name as product_name
from product p
left join offer o
on o.product_id = p.id
and o.offer = (select max(o1.offer) from offer o1 where o1.product_id = p.id)
我正在使用产品 ID 加入产品 table 并提供报价 table,我的要求是获得该产品的最高报价 (%),同时我想按条款分组产品 ID,因为我不想重复产品,但它显示错误的报价 ID,因为首先根据产品 ID 执行加入查询:
产品table:
id name
1 abc
2 xyz
出价table
id to_date product_id offer
1 2020-12-18 1 30%
2 2020-12-18 1 40%
3 2020-12-18 2 30%
4 2020-12-18 2 40%
查询:
SELECT product_id,product.name,o.id as offer_id,o.to_date, max(o.offer)offer_price
FROM products
LEFT JOIN offers o ON o.product_id=product.id
GROUP BY product.id
有问题的输出(错误的报价 ID):
offer_id product_id to_date offer_price
1 1 2020-12-18 40%
3 2 2020-12-18 40%
预期输出(正确的报价 ID)
offer_id product_id to_date offer_price
2 1 2020-12-18 40%
4 2 2020-12-18 40%
您可以使用 window 函数:
select o.*, p.name as product_name
from product p
left join (
select o.*,
row_number() over(partition by product_id order by offer desc) rn
from offer o
) o on o.product_id = p.id and o.rn = 1
row_number()
通过降序 offer
对具有相同 product_id
的记录进行排名 - 因此每个产品报价最高的行获得排名 1
。然后您可以使用该信息进行过滤。
这需要 MySQL 8.0。在早期版本中,一种替代方法使用相关子查询来过滤每个产品的最大报价:
select o.*, p.name as product_name
from product p
left join offer o
on o.product_id = p.id
and o.offer = (select max(o1.offer) from offer o1 where o1.product_id = p.id)