选择所有打开代码的记录,但是没有关闭的日期晚于打开?

时间:2013-12-13 12:48:00

标签: sql-server-2008 join

我有一个包含以下数据的表

AccountNo Code    Date
123456    OpenCS  01/12/2013
123456    CloseCS 03/12/2013
123456    CALLIN  11/10/2013
123456    CloseCS 08/08/2009
111587    OpenCS  12/12/2013
111587    CloseCS 01/12/2013

我需要获得的是具有完整OpenCS代码的所有帐户,但OpenCS之后没有CloseCS

所以我有2个选择查询

Select AccountNo, Code, Date FROM tblTrans
WHERE Code = ‘OpenCS’

Select AccountNo, Code, Date FROM tblTrans
WHERE Code = ‘CloseCS’

我正在加入这些以获取所需的数据。尝试了几个连接,但不能让选择排除记录。

因此,只有在开放前完成关闭时,它才会返回账户111587。

2 个答案:

答案 0 :(得分:2)

使用NOT EXISTS

SELECT t.* 
FROM tblTrans t
WHERE Code = 'OpenCS' 
AND NOT EXISTS
(
   SELECT 1 FROM tblTrans t2
   WHERE t2.AccountNo = t.AccountNo
   AND   t2.Date > t.Date
   AND   t2.Code = 'CloseCS'
)

Demo

ACCOUNTNO   CODE    DATE
111587     OpenCS   December, 12 2013 00:00:00+0000

在这方面值得一读:should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?(结论:不存在通常是你最好的选择)

答案 1 :(得分:0)

SELECT t1.AccountNo 
FROM tblTrans T1
INNER JOIN tblTrans T2 ON T1.AccountNo = T2.AccountNo
WHERE T1.Code = 'OpenCS' AND T2.Code = 'CloseCS' AND T2.Date < T1.Date