table 中的 Select 行,其中列中的值出现

Select rows from table where value in column appears ones

我有以下 table 三个字段,如下所示:

Table : Testing

create table testing
(
   colnum varchar(10),
   coldate date,
   colid int
);

插入:

insert into testing values('111','2015-01-01',1);
insert into testing values('111','2015-01-02',1);
insert into testing values('111','2015-01-03',1);
insert into testing values('111','2015-01-04',1);
insert into testing values('111','2015-01-05',1);
insert into testing values('222','2015-01-01',1);
insert into testing values('333','2015-01-01',1);

索引创建:

create clustered index id_idx on testing(colid);
create nonclustered index date_nidx on testing(coldate);
create nonclustered index num_nidx on testing(colnum);

注意: 现在我想显示只在特定日期和特定ID而不是其他日期的记录。

例如:我想显示 仅在 指定日期和 ID 但不显示其他日期的记录。

指定日期:2015-01-01
给定 ID:1

为此我编写了以下查询:

select * from testing
where coldate in ('2015-01-01')
      and coldid = 1
      and colnum not in(select colnum from testing where coldid = 1 and
                        coldate in('2015-01-02','2015-01-03','2015-01-04'
                             '2015-01-05');

结果:

colnum   coldate     colid
--------------------------
222     2015-01-01    1
333     2015-01-01    1

解释:查询显示两条记录,因为两条记录都只有特定日期和id 但是记录111未显示,因为它也属于其他日期,正如您在上面看到的 table.

上面的查询对我来说工作正常但是需要更多的时间来执行数十亿条记录。

试试这个 following.you 也会得到记录 111。

select * 来自测试

其中 coldate = '2015-01-01'

和 colid = 1;

对于执行时间,您只需在其上创建一个索引table.so它会提高您的执行性能。

谢谢。

我根据你例子中的结果做了一些假设。

  • 您想要特定日期而不是其他日期
  • 你想要所有的 colid(s)(按照你的例子)

你能检查一下这是否是预期的结果吗?

SELECT t.* 
FROM   testing t 
       LEFT JOIN (SELECT * 
                  FROM   testing 
                  WHERE  coldate <> '2015-01-01') x 
              ON x.colnum = t.colnum 
WHERE  x.colnum IS NULL 

试试这个查询:

SELECT colnum, coldate,colid 
FROM 
( 
 select *,COUNT(1) OVER (PARTITION BY colnum) as cnt 
from (SELECT DISTINCT colnum, coldate,colid from testing ) t
) q
where  q.cnt=1 and q.coldate in ('2015-01-01') and q.colid = 1

fiddle link: http://sqlfiddle.com/#!6/650c0/4

将速度与此进行比较会很有趣:

SELECT colnum,colid, min(coldate) as coldate
FROM testing 
GROUP BY colnum,colid
HAVING COUNT(DISTINCT coldate) = 1 
  AND colid = 1
  AND min(coldate) = '2015-01-01'