I'm trying to build a query where by I can extract the lowest price in the table, where the price is at least 10% or more of all the prices in the table.
I understand I can use MIN(price) to get the bottom rate in the table. However, I want to use the query to display a form price to the user which represents the lowest majority price.
This means it's fair, and demonstrates to the user that it's a realistic from price. As oppose to one product that might only be available once, and the likelihood is they'll never get that rate.
The price table is simple.
product_id, price.
It has thousands of rates, and I feel putting the lowest rate using MIN is misleading.
I'm really looking for some example queries of how others might tackle this. Is it possible in a single query?
Here we use
rank() over partition byin a cte to number the records of each productID from lowest to highest. We thank take the lowest price where the rank number is higher than one tenth of the number of records for that article. If there are less than 10 records it will be the lowest price.Below I have put the query from the CTE on it's own to show how it works. Finally there is the link to DBfiddle for the test schema.
db<>fiddle here