2013-12-17 42 views
0

我有一張桌子,下面設置了我想要提取的是所有擁有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

您的桌子上沒有「FA」列。 'WHERE'語句中'CODE'列不明確的第一行應該是'mx.Code'或'm.Code' – Yaroslav

回答

0

爲了讓那些有DIS在過去五天

select accountNo from accounts where acc.code = 'DIS' and acc.date > GETDATE()-5 

賬戶要獲得那些具有

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) 
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