0

我有两个表 ( IncomingDocs) 和 ( OutgoingDocs),每个表都有一个名为SubmitDate(datatype Datetime) 和DepositNo(datatype Int) 的字段,每个表都可以在一个表中 DeposotNo有多个。Submitdate

    For example;



_IncomingDocs table_

**DepositNo**  |  **SubmitDate**  

    1  |  10/3/2012 12:00:00 AM  
    1  |  12/3/2012 12:00:00 AM  
    2  |  10/3/2012 12:00:00 AM  
    3  |  10/3/2012 12:00:00 AM  
    3  |  13/3/2012 12:00:00 AM  
    4  |  20/3/2012 12:00:00 AM  

_OutgoingDocs table_

**DepositNo**  |  **SubmitDate**  

    1  |  11/3/2012 12:00:00 AM  
    2  |  15/3/2012 12:00:00 AM  
    3  |  12/3/2012 12:00:00 AM  
    3  |  14/3/2012 12:00:00 AM  
    4  |  19/3/2012 12:00:00 AM  

    SELECT DepositNo, SubmitDate  
    FROM IncomingDocs AS i, OutgoingDocs as o  
    WHERE DepositNo = 1  
    ORDER BY SubmitDate  

* The output of the query should be:

_Output table_

**DepositNo**  |  **SubmitDate**  
1  |  10/3/2012 12:00:00 AM  << From IncomingDocs table  
1  |  11/3/2012 12:00:00 AM  << From OutgoingDocs table  
1  |  12/3/2012 12:00:00 AM  << From IncomingDocs table 

我希望输出是特定 DepositNo 的记录(在 WHERE 子句中指定)并按提交日期排序。

4

2 回答 2

3

我不确定sql server是否支持联合,但是像这样

Select DepositNo, SubmitDate from IncomingDocs where DepositNo = X
UNION
Select DepositNo, SubmitDate from OutgoingDocs where DepositNo = X
ORDER BY SubmitDate

应该可以工作。

于 2012-11-25T09:57:59.093 回答
3

-- 如果您需要保留每个表中的两行 -- 碰巧是重复的,您将需要 'UNION ALL'

SELECT DepositNo, SubmitDate  
FROM (  
     SELECT DepositNo, SubmitDate  
     FROM OutgoingDocs  
     WHERE DepositNo = 1 --Or a variable @MyDepositNo  
     UNION ALL --this will preserve duplicate rows if there are any between the two tables  
     SELECT DepositNo, SubmitDate  
     FROM IncomingDocs  
     WHERE DepositNo = 1 --as above  
) TT  
ORDER BY TT.SubmitDate  
于 2012-11-25T10:54:33.707 回答