I have a table like so:

order_id INT product_id INT average_price DOUBLE other_price DOUBLE

There are multiple product_ids per order_id i.e. multiple products per order. I want to the product with the minimum average price per order and out of these products those for which other_price >= average_price.

I've tried this:

SELECT a.order_id, a.product_id, a.average_price, a.other_price
FROM
    (SELECT order_id, product_id, min(average_price) as average_price
     FROM orders
     GROUP BY order_id
    ) as min_priced_product_per_order
JOIN orders AS a ON a.order_id = min_priced_product_per_order.order_id and min_priced_product_per_order.product_id = min_priced_product_per_order.product_id 
WHERE a.other_price >= a.average_price

But the results are not what I expected, I am not convinced that I am getting the product_id with the minimum average price for each order (I've confirmed by inspecting the DB).

Can you suggest a better query?

Cheers.

Pete

没有正确的解决方案

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top