SQL从单行中选择2列作为列表

时间:2016-06-02 12:50:24

标签: sql sql-server union

我有一个包含[From], [To]列的表格。我需要选择这些列作为单个列表,我这样做:

SELECT [From] FROM [TableX] WHERE (...)
UNION
SELECT [To] FROM [TableX] WHERE (...)

问题在于我不想复制WHERE (...)条件,因为它很长。有没有办法避免这种重复?

2 个答案:

答案 0 :(得分:3)

使用CTE防止重复WHERE条件:

;WITH [CTE_Criteria] AS (
    SELECT [From], [To]
    FROM [TableX]
    WHERE (...)
)
SELECT [From] FROM [CTE_Criteria]
UNION
SELECT [To] FROM [CTE_Criteria];

答案 1 :(得分:1)

在派生表中执行UNION,并且有一个共同的WHERE子句。

select *
from
(
    SELECT [From] FROM [TableX] 
    UNION
    SELECT [To] FROM [TableX]
)
WHERE (...)