假设我在同一张表中有以下两列
Column 1
--------
1
2
3
Column 2
--------
4
5
6
我如何得到一个给我的结果:
Columns
--------
1
2
3
4
5
6
编辑
我真正要寻找的是确保没有一种更有效的方法可以在同一个表中的多个列上键入联合查询,而不必多次重复它是哪个表并为每个联合多次重复 where 条件.
实际查询看起来更像这样:
WITH T1 AS
( SELECT [Col1] FROM [Table1]
)
SELECT * FROM (
SELECT [Cols1-100], COUNT(*) as "Count" FROM (
SELECT [Col-1] FROM [Table2] AS [Cols1-100], [T1]
WHERE [Table2].[Col-1] = [T1].[Col-1]
AND [Col-1] != '2' AND [Col-2] != '2' ..... etc ..... AND [Col-100] != '2'
UNION ALL
SELECT [Col-2] FROM [Table2] AS [Cols1-100], [T1]
WHERE [Table2].[Col-1] = [T1].[Col-1]
AND [Col-1] != '2' AND [Col-2] != '2' ..... etc ..... AND [Col-100] != '2'
UNION ALL
....................... etc
....................... etc
....................... etc
.... etc
SELECT [Col-100] FROM [Table2] AS [Cols1-100], [T1]
WHERE [Table2].[Col-1] = [T1].[Col-1]
AND [Col-1] != '2' AND [Col-2] != '2' ...... etc .... AND [Col-100] != '2'
) as [Temp1]
GROUP BY [Cols1-100]
) as [Temp2]
使用@Bohemian Outer Query 我可以执行以下操作,但测试两个查询,它似乎慢了很多。
WITH T1 AS
( SELECT [Col1] FROM [Table1]
)
SELECT * FROM (
SELECT [Cols1-100], COUNT(*) as "Count" FROM (
SELECT * FROM (
SELECT [Col-1] AS [Cols1-100], [Col-1], [Col-2], ..etc.. [Col-100] FROM [Table2]
UNION ALL
SELECT [Col-2] AS [Cols1-100], [Col-1], [Col-2], ..etc.. [Col-100] FROM [Table2]
UNION ALL
....................... etc
.... etc
SELECT [Col-100] AS [Cols1-100], [Col-1], [Col-2], ..... etc ..... [Col-100] FROM [Table2]
) AS SUBQUERY WHERE [Col-1] IN (SELECT [Col1] FROM [T1])
AND [Col-1] != '2' AND [Col-2] != '2' ..... etc ..... AND [Col-100] != '2'
) as [Temp1]
GROUP BY [Cols1-100]
) as [Temp2]