Skip to content
Advertisement

Query puzzle – how can I select values with fallbacks?

I have a table with 6 columns as follows:

For searching I am providing target values for B/C/D and selecting columns A and E for a result set.

I would like to obtain a row if:

  • B/C/D all match provided values => select it
  • B/C match but D is NULL => select it
  • B/D match but C is NULL => select it
  • B matches and C/D are NULL as a final fallback.

Basically I would like to get a row if conditions are hit in order (eg: if I have a match for all 3, I don’t want a result from the next condition)

So far the closes I’ve come is this:

However, I do run into the issue that I get multiple records when C/D are both NULL + C has matching value and D is NULL.

Can someone suggest what I can do?

Thanks!

Advertisement

Answer

You can create a column for each of your conditions, sort the results by the priority of each condition and return the 1st row only:

Or:

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