eatonphil eatonphil - 3 months ago 28
SQL Question

SQL - Execute SQL query on SQL query

Is it possible to run a SQL query on another SQL query?
I have a SQL query that compiles many columns into one using a Union All clause. I need to use a group clause but you will see that that is not possible. Is there any way to run another SQL query on this one?

Query:

Select Ins1 as Insurance

From InsAuth2
WHERE Ins1 IS NOT NULL
Group By Ins1
Union All
Select Ins2 as Insurance
From InsAuth2
WHERE Ins2 IS NOT NULL
Group By Ins2
Union All
Select Ins3 as Insurance
From InsAuth2
WHERE Ins3 IS NOT NULL
Union All
Select Ins4 as Insurance
From InsAuth2
WHERE Ins4 IS NOT NULL
Union All
Select Ins5 as Insurance
From InsAuth2
WHERE Ins5 IS NOT NULL


I need to be able to select unique values from this compiled column. I could use a group by in every statement, however that would only return unique values from the original column. The compiled column could potentially not have all unique values if values unique to one column were also unique to another. Therefore I must have another SQL query operating on this one. Any suggestions?

Answer

Use an inner query i.e.

SELECT *
FROM
(
    YourQueryHere
) Inn
GROUP BY YourColumnHere