从两个不同的表T-SQL中选择相同的列

时间:2012-09-27 14:59:45

标签: tsql

我需要从两个不同的表中获取一个名为SymNumber的列。两者都将使用类似的标准进行选择。以下是我到目前为止所做的工作......

DECLARE @date datetime

SELECT @date = LastChangeDate
FROM QueueUpdates

SELECT DISTINCT u.CompanyCode, u.AgentId 
FROM SymNumberToAgentId u, AgentIdToTradingPartner a, TradingPartner t, AgentContEd c 
WHERE u.SymNumber in 
(SELECT SymNumber FROM 
(SELECT a.SymeNumber, c.SymNumber 
FROM AgentProductTraining a, AgentContEd c 
WHERE a.LastChangeDate >= @date and c.LastChangeDate >= @date) a ) and 
u.AgentId = a.AgentId and a.TradingPartnerCode = t.TradingPartnerCode and t.TradingPartnerCode = 'SE2'

GO

令我头疼的部分是下面列出的内部查询。我认为调整这部分将允许我从两个表中获取SymNum列。

(SELECT SymetraNumber FROM 
(SELECT a.SymetraNumber, c.SymetraNumber 
FROM AgentProductTraining a, AgentContEd c 
WHERE a.LastChangeDate >= @date and c.LastChangeDate >= @date) a )

1 个答案:

答案 0 :(得分:4)

UNIONUNION ALL在这里看起来很不错:

(
    SELECT SymetraNumber 
    FROM AgentProductTraining a
    WHERE a.LastChangeDate >= @date 
    UNION
    SELECT SymetraNumber 
    FROM AgentContEd c 
    WHERE c.LastChangeDate >= @date
)