Skip to content
Advertisement

Show TOP 1 considering where condition if present -SQL query

I have a case where I am using a OUTER APPLY query as below

But I have new requirement where OUTER APPLY should happen based on considering customer_category = 'General' if present.

Pseudo code will be like as below

Can anyone suggest better way to rewrite outer apply code in efficient way.

Advertisement

Answer

You can combine your conditions by adding an order by clause to your outer apply query to prioritise CUSTOMER_CATEGORY = 'General' e.g.

The result of the case expression when CUSTOMER_CATEGORY like '%General%' is 1 and 0 otherwise. We then order by the result of the case expression in a descending manner i.e. highest to lowest. In summary this means that if the CUSTOMER_CATEGORY like '%General%' it will select selected as a priority.

To further understand how this works consider the results produced by:

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