Skip to content
Advertisement

How do I find the maximum depending on multiple subranges within one column

I have two tables: Orders and Customers. Orders lists all bought items (policy_id) and Customers information such as their age. The two tables are linked via the customer_id. Now I want to find the most popular items within 3 age groups (18-30, 31-60, >60). How do I approach this problem?

The following gives me a list of all items and their popularity split into the age groups but I only want the most popular ones per age group.

Do I need to add something or am I on the completely wrong track?

Advertisement

Answer

You can use window functions for this. You can do so right along with the aggregation. For the top policy_id per age range:

If you want a different number, just change the WHERE clause.

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