是否可以在另一个SQL查询上运行SQL查询?我有一个SQL查询,它使用Union All子句将多个列编译成一个列。我需要使用group子句,但您将看到这是不可能的。有没有办法在这个查询上运行另一个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查询在这个查询上操作。有什么建议吗?
发布于 2012-07-25 22:54:53
使用内部查询,即
SELECT *
FROM
(
YourQueryHere
) Inn
GROUP BY YourColumnHere
发布于 2012-07-25 22:54:13
使用派生表和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
发布于 2012-07-25 22:59:45
如果您使用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
https://stackoverflow.com/questions/11652514
复制相似问题