当产品是组时,选择价格最小的产品

时间:2017-11-13 14:38:05

标签: mysql subquery inner-join

按组ID选择价格最便宜的产品。 当一组中的所有产品具有不同的价格时,我设法得到最便宜的产品,但是当一组中的所有产品具有相同的价格时它不起作用。所以

我需要帮助添加额外的过滤器以限制加入。

http://sqlfiddle.com/#!9/f9b16c/6

I have created a sample here.

SELECT 
    p.id, p.price
FROM
    product p
        JOIN
    (SELECT 
        product_group_id, MIN(price) AS price
    FROM
        product
    GROUP BY product_group_id

    ) AS inp ON p.product_group_id = inp.product_group_id
        AND p.price = inp.price;

示例数据

ID |价格| sku | product_group_id

'58', '2800.0000', '1-67-131-72', '44'
'60', '3688.0000', '8-105-82-72', '30'
'61', '2750.0000', '9-105-82-72', '31'
'62', '3400.0000', '10-67-131-72', '45'
'189', '3530.0000', '7-113-114-115', '29'
'190', '3050.0000', '7-113-114-72', '29'
'193', '2980.0000', '7-105-114-115', '29'
'194', '2500.0000', '7-105-114-72', '29'
'196', '4699.0000', '8-116-114-115', '30'
'199', '4069.0000', '8-116-82-72', '30'
'200', '4318.0000', '8-105-114-115', '30'
'205', '3910.0000', '9-117-82-115', '31'
'206', '3230.0000', '9-117-82-72', '31'
'207', '3580.0000', '9-105-114-115', '31'
'256', '3550.0000', '1-135-136-137', '44'
'257', '3070.0000', '1-135-136-72', '44'
'258', '3400.0000', '1-135-131-137', '44'
'259', '2920.0000', '1-135-131-72', '44'
'260', '3430.0000', '1-67-136-137', '44'
'261', '2950.0000', '1-67-136-72', '44'
'262', '3280.0000', '1-67-131-137', '44'
'263', '3880.0000', '10-67-131-137', '45'
'292', '8750.0000', 'HobartAUPs-117-137', '53'
'293', '8750.0000', 'HobartAUP-69-72', '53'
'294', '8750.0000', 'HobartAUP-69-137', '53'
'295', '8750.0000', 'HobartAUP-117-72', '53'

期望的结果

ID |价

'194', '2500.0000'
'61', '2750.0000'
'58', '2800.0000'
'62', '3400.0000'
'60', '3688.0000'
'292', '8750.0000'

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您只想获得价格最低的一行。因此,当您在一个组中有多个具有相同价格的行时,您需要确定所需的行。也许最少id

select min(p.id) as id,
    p.price
from product p
join (
    select product_group_id,
        min(price) as price
    from product
    group by product_group_id
    ) as inp
on  p.product_group_id = inp.product_group_id
    and p.price = inp.price
group by p.price, p.product_group_id;