在JOIN查询中使用2个UNION命令

时间:2015-06-27 06:16:47

标签: sql-server

我正在尝试使用下面的JOIN查询从2个相同的Current和Archive表中检索数据。但是,这会返回2个结果集,并且也不会返回存档表中的数据(我确定这是因为我在JOIN命令中引用了&n;&n; 39&n; 39',但我没有&# 39;知道如何引用这两个表格。

我已尝试过每个查询组合,但没有成功。我做错了什么?

SELECT N.TranType,N.UserNo,N.TranCode
FROM (SELECT TranType,UserNo,TranCode FROM nTrans 
UNION ALL SELECT TranType,UserNo,TranCode FROM nTransArc) 
AS N
SELECT H.HeaderKey 
FROM (SELECT HeaderKey FROM MoveHdr
UNION ALL SELECT HeaderKey FROM MoveHdrArc) 
AS H
JOIN nTrans N ON H.HeaderKey = N.TranType + N.UserNo + N.TranCode 

1 个答案:

答案 0 :(得分:2)

我想你想要这个:

SELECT N.TranType, N.UserNo, N.TranCode
FROM (SELECT TranType, UserNo, TranCode FROM nTrans 
      UNION ALL 
      SELECT TranType, UserNo, TranCode FROM nTransArc) AS N
JOIN (SELECT HeaderKey FROM MoveHdr
      UNION ALL
      SELECT HeaderKey FROM MoveHdrArc) AS H
ON H.HeaderKey = N.TranType + N.UserNo + N.TranCode