Skip to content
Advertisement

SELECT Only Cheapest Or Most Expensive Variant From Many

I have a table of product variants, grouped by a product key. I also have a category table which is joined off the ProductKey. So if I query for products in a category or many categories I will get a list variants that match the joined ProductKeys.

Which would result in example data like this

The issue is I just want to return a single product per ProductKey. Either the cheapest of the group. So the results would be

Or the most expensive. So the results would be

How can I do this efficiently within the SELECT sql query? Currently I’m returning all and doing the filtering in memory on the server in C#.

Advertisement

Answer

If I understand you correctly, you need to use ROW_NUMBER() to get the expected results:

Table:

Statement for the cheapest product:

Statement for the most expensive product:

Results:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement