Skip to content
Advertisement

sql – Get the Minimum Value of 2 subqueries

I have a query which has 5 subqueries. I need it to have only 4 subqueries, since two of them are supposed to be only one result. The problem is I don’t know how to maintain the query structure and get the MIN value of 2 of those subqueries. This is my query:

And I need to get the minimum value of the 3rd and 4th subqueries instead of adding both of them to the SUM(Stock) of the main query. How can I achieve that? I need to maintain the query structure.. I need the MIN from the Result of those queries (3rd and 4th):

Advertisement

Answer

Consider turning subqueries into multiple CTEs, then in UNION query add columns for Stock3 and Stock4 based on corresponding Stock to aggregate for MIN values, filling in NULLs for other queries:

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