假设我在同一个表中有以下两列
Column 1
--------
1
2
3
Column 2
--------
4
5
6
Run Code Online (Sandbox Code Playgroud)
我如何得到一个给我的结果:
Columns
--------
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
编辑
我真正想要的是确保没有更有效的方法在同一个表中的多个列上键入联合查询,而不必多次重复哪个表并多次重复每个联合的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]
Run Code Online (Sandbox Code Playgroud)
使用@Bohemian外部查询我可以执行以下操作,但测试两个查询,它似乎慢了很多.
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]
Run Code Online (Sandbox Code Playgroud)
select column1 as columns from mytable
union
select column2 from mytable
Run Code Online (Sandbox Code Playgroud)
使用union
删除重复项(并在某些数据库上也排序).
如果要保留重复项,请使用union all
:
select column1 as columns from mytable
union all
select column2 from mytable
Run Code Online (Sandbox Code Playgroud)
要添加where子句,简单但低效的执行方式是将其添加为外部查询:
select * from (
select column1 as columns from mytable
union
select column2 from mytable ) x
where columns ...
Run Code Online (Sandbox Code Playgroud)
更有效的执行方式,但是一个痛苦的长查询,是将它放在每个子查询上:
select column1 as columns from mytable
where ....
union
select column2 from mytable
where ...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
34179 次 |
最近记录: |