从表中选择行,其中列中的值显示为1

时间:2015-07-29 16:04:15

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

我的下表有三个字段,如下所示:

表: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,因为它也属于其他您可以在上表中看到日期。

以上查询适用于我需要更多时间执行数十亿条记录。

4 个答案:

答案 0 :(得分:2)

尝试此查询:

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

小提琴链接:http://sqlfiddle.com/#!6/650c0/4

答案 1 :(得分:1)

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

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

请检查这是否是预期结果?

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 

答案 2 :(得分:0)

请尝试以下操作。您也将获得记录111。

从测试中选择*

冷静=&#39; 2015-01-01&#39;

和colid = 1;

并且对于执行时间,您只需在该表上创建索引。这样可以提高执行性能。

感谢。

答案 3 :(得分:0)

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

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'
相关问题