Skip to content
Advertisement

Select ans specific value or, if not exists, the minimum one

I’m stuck trying to solve a problem using SQL (MySQL 5.6). Need to get the address which has ID 2 or, if not exists ID 2, the lower ID.

For example

If a costumerID have an AddressID 2, must get that. If not, must get the minimum AddressID. The output must be like:

So far I’ve tried this:

but get duplicates at CostumerID.

Advertisement

Answer

Use aggregation with CASE logic:

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