SQL Select: picking the right distinct record based on another field
How does one filter a list of records to remove those that have some identical fields, based on selecting the one with the minimum value in another field? Note that it's not sufficient to just get the minimum value... I need to have other fields from the same record.
I have a table of "products", and I am trying to add the ability to apply a coupon code. Because of how the invoices are generated, selling a product at a different cost is considered a different product. In the database you might see this:
Product ID, Product Cost, Product Name, Coupon Code
1, 20, Product1, null
2, 10, Product1, COUPON1
3, 40, Product2, null
I have a query that selects a list of all products available now (based on other criteria; I'm simplifying this a lot). The problem is that, for the above case, my query returns:
1 - Product1 for $20
2 - Product1 for $10
3 - Product2 for $40
This gets shown to the customer (assuming they've entered the coupon code), and it's obviously bad form to show a customer the same product for two prices. What I want is:
2 - Product1 for $10
3 - Product2 for $40
i.开发者_开发问答e., showing the lowest-costing version of each product.
I need a solution that will work for MySQL, but the preferred solution would be standard SQL.
Try this:
SELECT T2.*
FROM
(
SELECT `Product Name` AS name, MIN(`Product Cost`) AS cost
FROM products
GROUP BY `Product Name`
) T1
JOIN products T2
ON T1.name = T2.`Product Name`
AND T1.cost = T2.`Product Cost`
To get the output exactly as you described as a string replace the first line with:
SELECT CONCAT(`Product ID`, ' - ', T1.name, ' for $', T1.cost)
精彩评论