3

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?

2
  • 1
    Yes you can. Just do an outer query with group by on appropriate column Commented Jul 25, 2012 at 14:54
  • You can execute a query on a list returned from select if you just put your query in From. Commented May 30, 2018 at 13:03

4 Answers 4

6

Use an inner query i.e.

SELECT *
FROM
(
    YourQueryHere
) Inn
GROUP BY YourColumnHere
Sign up to request clarification or add additional context in comments.

Comments

3

Use derived table and distinct:

select distinct Insurance
from
(
  Select Ins1 as Insurance
  From InsAuth2
  WHERE Ins1 IS NOT NULL
  Union All
  Select Ins2 as Insurance
  From InsAuth2
  WHERE Ins2 IS NOT NULL
  ...
) table_alias

Comments

3

If you use UNION instead of UNION ALL it will filter out duplicates

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

Comments

0

Try using UNION instead of UNION ALL

Thanks

3 Comments

should be a comment.
Try the following:
Try the following: Select Ins1 as Insurance From InsAuth2 WHERE Ins1 IS NOT NULL Union Select Ins2 as Insurance From InsAuth2 WHERE Ins2 IS NOT NULL Union Select Ins3 as Insurance From InsAuth2 WHERE Ins3 IS NOT NULL Union Select Ins4 as Insurance From InsAuth2 WHERE Ins4 IS NOT NULL Union Select Ins5 as Insurance From InsAuth2 WHERE Ins5 IS NOT NULL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.