Skip to content
Advertisement

Getting a distinct value from one column if all rows matches a certain criteria

I’m trying to find a performant and easy-to-read query to get a distinct value from one column, if all rows in the table matches a certain criteria.

I have a table that tracks e-commerce orders and whether they’re delivered on time, contents and schema as following:

I would like to get all distinct customer_id’s which have had all their orders delivered on time. I.e. I would like an output like this:

What’s the best way to do this?

I’ve found a solution, but it’s a bit hard to read and I doubt it’s the most efficient way to do it (using double CTE’s):

Advertisement

Answer

You use group by and having as follows:

This works because an ontime delivery is identified by delivered_on_time = 1. So you can just ensure that the sum of delivered_on_time is equal to the number of records for the customer.

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