2016-01-25 39 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