Skip to content
Advertisement

Best way to merge two SQL queries into one query

I have two small SQL queries that I would like to merge to be a single query that I will eventually use in a stored procedure. I have tried a CASE and IF/ELSE but could not get it to work. Below is the code. What I want to achieve is have the first column ‘Count of Open Order Lines’ based on both where statements from both queries but the second column ‘Sum Quantity’ only based on the where statement from the second query.

Advertisement

Answer

You need conditional aggregation:

In the WHERE clause I kept only the condition OO.ORST BETWEEN 22 AND 66 which is common in both queries and for Count of Open Order Lines I used a CASE expression based on the condition OH.OBLC BETWEEN 1 AND 8.

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