查询以查找不匹配的Doctype ID

时间:2016-01-25 10:00:18

标签: sql sql-server sql-server-2008

我有一个名为Documents的表,其中包含以下列。

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 个答案:

答案 0 :(得分: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) 

答案 1 :(得分:0)

你可以尝试:

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