选择具有某些值但同时没有其他值的记录

时间:2018-01-29 01:50:24

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

开始之前,谢谢你的帮助。

我的问题是:我有一个表格,例如activity_records,其中包含date列和activity_id列。

我只想选择那些日期,例如activity_id值为1但在任何其他记录中都没有2的日期日期。

我尝试了多选查询等等。

4 个答案:

答案 0 :(得分:1)

一种方法使用not exists

select ar.*
from activity_records ar
where ar.activity_id = 1 and
      not exists (select 1
                  from activity_records ar2
                  where r2.date = ar.date and ar2.activity_id = 2
                 );

因为您只想要日期,所以选择group by

select ar.date
from activity_records ar
group by ar.date
having sum(case when ar.activity_id = 1 then 1 else 0 end) > 0 and
       sum(case when ar.activity_id = 2 then 1 else 0 end) = 0;

或者,最简单的就是这个特例:

select ar.date
from activity_records ar
where ar.activity_id in (1, 2)
group by ar.date
having max(ar.activity_id) = 1 ;

答案 1 :(得分:0)

SELECT [date] FROM [activity_records] WHERE [activity_id] = 1
EXCEPT
SELECT [date] FROM [activity_records] WHERE [activity_id] = 2

有关更复杂的方案,另请参阅WHERE NOT EXISTSAPPLY

答案 2 :(得分:0)

另一种方法是仅使用一个不同activity_id的日期,然后通过自我加入过滤activity_id = 1的日期。

SELECT DISTINCT B.DATE
FROM
(SELECT DATE, COUNT(DISTINCT ACTIVITY) AS COUNT_ACTIVITIES
FROM YOUR_TABLE
GROUP BY DATE
HAVING COUNT(DISTINCT ACTIVITY) = 1) A
INNER JOIN
YOUR_TABLE B
ON A.DATE = B.DATE
AND B.ACTIVITY_ID = 1;

答案 3 :(得分:0)

一种不使用的方法:

从activity_records ar中选择ar。*,其中ar.activity_id = 1且ar.date不在(从activity_records ar2中选择ar2.date,其中ar2.activity_id = 2);