2016-01-25 70 views
-4

我有一張名爲Documents的表,其中有以下幾列。查詢找不到匹配的文檔類型ID

DocID,DocTypeID,Invoice,Invoice_Date 

我要找的是讓出現在DocTypeID 5bef8666,但不會出現在DocTypeID 923847f9所有發票。

DocID,DocTypeID,Invoice,Invoice_Date 
00001,923847f9, 00001 ,24/01/2016 
00002,923847f9, 00002 ,24/01/2016 
00003,923847f9, 00003 ,24/01/2016 
00004,923847f9, 00004 ,24/01/2016 
00005,5bef8666, 00005 ,24/01/2016 
00001,5bef8666, 00001 ,24/01/2016 
00002,5bef8666, 00002 ,24/01/2016 
00003,5bef8666, 00003 ,24/01/2016 
00004,5bef8666, 00004 ,24/01/2016 

結果

DocID, DocTypeID, Invoice, Invoice_Date 
00005, 5bef8666, 00005, 24/01/2016 

這是我至今沒有結果嘗試。

SELECT * 
FROM Documents d1 
WHERE d1.DocTypeID = ' 5bef8666' 
     AND NOT EXISTS (SELECT 1 
         FROM Documents d2 
         WHERE d2.DocTypeID = '923847f9' 
         and d2.Invoice = d1.Invoice); 

在此先感謝您。

+2

請發表你已經嘗試了嘗試,並解釋哪裏出了問題 – Peter

+0

@ user3309798最簡單的where子句'如果DocTypeID ='5bef8666'' – tchelidze

+0

SQL中where子句的用法是什麼? – Anil

回答

0

你可以嘗試這樣的,

Declare @Documents table(
DocID varchar(10),DocTypeID varchar(10),Invoice varchar(10),Invoice_Date varchar(10)) 

insert into @documents values 
('00001','923847f9','00001','24/01/2016'), 
('00002','923847f9','00002','24/01/2016'), 
('00003','923847f9','00003','24/01/2016'), 
('00004','923847f9','00004','24/01/2016'), 
('00005','5bef8666','00005','24/01/2016'), 
('00001','5bef8666','00001','24/01/2016'), 
('00002','5bef8666','00002','24/01/2016'), 
('00003','5bef8666','00003','24/01/2016'), 
('00004','5bef8666','00004','24/01/2016') 

SELECT * 
FROM @documents d1 
WHERE d1.DocTypeID = '5bef8666' 
     AND NOT EXISTS (SELECT 1 
         FROM @documents d2 
         WHERE d2.doctypeid = '923847f9' 
           AND d1.docid = d2.docid) 
+0

嗨@NewUser,上面給了我零條目,但我知道我有1條記錄沒有在DoctypeID 923847f9中顯示,但它在5bef8666? – user3309798

+0

我編輯了我的答案,請現在查看演示。查詢是正確的。但是你在where子句過濾器中給了額外的空間(d1.DocTypeID ='5bef8666')。請刪除5bef8666之前的空格。 – StackUser

+0

謝謝@NewUser,它現在可以工作 – user3309798

0

你可以試試:

select a.* from Documents a left join Documents b 
on a.DocID = b.DocID 
where a.DocTypeID="5bef8666" 
and b.DocTypeID is null 
+0

這個查詢也不會拉取所需的結果。如果您查看發票列,則會看到發票0005未出現在923847f9中,但出現在5bef8666中。 – user3309798

+0

當您嘗試我的解決方案時,結果如何? – Ariela

+0

結果發現零記錄。 – user3309798