我有一个下面设置的表格,我想要提取的是所有拥有HH1但在5天内没有DIS的帐户的列表。
AccountNo Code Date
125487 HH1 17/11/2013
125487 DIS 18/11/2013
123368 HH1 16/11/2013
124587 HH1 10/09/2013
我尝试使用NOT EXISTS,但是它只返回过去5天内的记录?
SELECT mx.AccountNo
, mx.Code
, mx.Date
FROM dbo.tblmtx AS mx INNER JOIN
dbo.tblM AS m ON m.AccountNo = mx.AccountNo
WHERE (Code IN ('HH1')) AND (FA = 'R') AND
(mx.Date > GETDATE()-5 )
AND
NOT EXISTS
( SELECT 1 FROM dbo.tblMaTx AS mx2
WHERE mx2.AccountNo = mx.AccountNo
AND mx2.Date >= GETDATE()-5
AND mx2.Code = 'DIS'
AND mx2.FA = 'R'
)
GROUP BY mx.AccountNo
, mx.Code
, mx.Date
ORDER BY mx.AccountNo
我哪里错了?
答案 0 :(得分:0)
获取过去五天内有DIS的帐户
select accountNo from accounts where acc.code = 'DIS' and acc.date > GETDATE()-5
获取DO所拥有的帐户
select accountNo from accounts where acc.code = 'HH1'
然后:
select accountNo from accounts where acc.code = 'HH1' and accounts.accountNo not in
(select accountNo from accounts acc2 where acc2.code = 'DIS' and
acc2.date > GETDATE()-5 )
答案 1 :(得分:0)
试试这个
SELECT a.AccountNo, a.Code, a.[Date]
FROM [YourTable] a
LEFT OUTER JOIN [YourTable] a2
ON a.AccountNo = a2.AccountNo
AND a2.[Date] BETWEEN DATEADD(day, -5, a.[Date]) AND a.[Date]
WHERE a.Code = 'HH1'
AND a2.AccountNo IS NULL