简体   繁体   English

SQL 根据日期范围的特定条件排除数据

[英]SQL Excluding data based on certain criteria for a date range

How to exclude records with certain values in sql select 如何排除sql select中某些值的记录

I need to exclude the entire month where Video or Face-to-Face exist but keep the months where either one of those options is not found.我需要排除存在视频或面对面的整个月份,但保留未找到其中任何一个选项的月份。 I'm using the NOT EXISTS which works but when I filter based on a date range, it excludes everything because it found a single instance somewhere in the date range我正在使用有效的 NOT EXISTS,但是当我根据日期范围进行过滤时,它排除了所有内容,因为它在日期范围内的某处找到了一个实例

C1 C1 c2 c2 c3 c3
149000 149000 2022-06-21 00:00:00.000 2022-06-21 00:00:00.000 Telephone电话
149000 149000 2022-06-21 00:00:00.000 2022-06-21 00:00:00.000 Video视频
149000 149000 2022-06-24 00:00:00.000 2022-06-24 00:00:00.000 Telephone电话
149000 149000 2022-07-08 00:00:00.000 2022-07-08 00:00:00.000 Telephone电话
149000 149000 2022-07-15 00:00:00.000 2022-07-15 00:00:00.000 Telephone电话
149000 149000 2022-07-22 00:00:00.000 2022-07-22 00:00:00.000 Telephone电话
149000 149000 2022-07-29 00:00:00.000 2022-07-29 00:00:00.000 Telephone电话
149000 149000 2022-08-12 00:00:00.000 2022-08-12 00:00:00.000 Telephone电话
149000 149000 2022-08-26 00:00:00.000 2022-08-26 00:00:00.000 Telephone电话
149000 149000 2022-09-01 00:00:00.000 2022-09-01 00:00:00.000 Face-to-Face面对面
149000 149000 2022-09-01 00:00:00.000 2022-09-01 00:00:00.000 Face-to-Face面对面
149000 149000 2022-09-12 00:00:00.000 2022-09-12 00:00:00.000 Telephone电话
149000 149000 2022-09-12 00:00:00.000 2022-09-12 00:00:00.000 Video视频

The two commented lines are tests lines to see what it would do to my results.两条注释行是测试行,用于查看它对我的结果有何影响。

SELECT 
    c1
    ,c2
    ,C3

FROM  a1

WHERE
not exists (SELECT * FROM a1 as B WHERE b.c1 = a1.c1 and (b.c3= 'Face-to-Face' or b.c3 = 'Video') )
--and a1.c2 between '2022-06-01' and '2022-06-30')    
--and a1.c2 = b.c2)

and c2 between '2022-01-01' and '2022-12-30'

This seems to work:这似乎有效:

SELECT c1, c2, c3
FROM a1
WHERE DATEPART(MONTH, c2) NOT IN (
    SELECT DATEPART(MONTH, c2) FROM a1 WHERE c3 IN ('Video', 'Face-to-Face')
)

Thank you both for your help.谢谢你们的帮助。 Helped me get where I needed to with my data.帮助我找到我需要的数据。

SELECT 
   c1
   ,c2
   ,C3

FROM  a1

WHERE
DATEADD(month, DATEDIFF(MONTH, 0, c2), 0) not in (
Select DATEADD(month, DATEDIFF(MONTH, 0, c2), 0) 
from a1 
where c1= a1.c1 and c3 IN ('Video', 'Face-to-Face'))

Maybe something like this?也许是这样的?

select main.* 
from a1 main
where extract(month from main.c2) not in(
    select extract(month from sub.c2)
    from a1 sub
    where sub.c3 in ('Video', 'Face-to-Face')
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM