是否可以在另一个SQL查询上运行SQL查询? 我有一个SQL查询,它使用Union All子句将许多列编译为一个。我需要使用组子句但你会发现这是不可能的。有没有办法在这个上运行另一个SQL查询?
查询:
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
我需要能够从此编译列中选择唯一值。我可以在每个语句中使用group by,但是只返回原始列中的唯一值。如果一列唯一的值对另一列唯一,则编译列可能不会具有所有唯一值。因此,我必须有另一个SQL查询在此操作。有什么建议吗?
答案 0 :(得分:6)
使用内部查询,即
SELECT *
FROM
(
YourQueryHere
) Inn
GROUP BY YourColumnHere
答案 1 :(得分:3)
使用派生表和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
答案 2 :(得分:3)
如果您使用UNION
代替UNION ALL
,则会过滤掉重复项
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
答案 3 :(得分:0)
尝试使用UNION而不是UNION ALL
由于