简体   繁体   English

SQL 如何使用 datediff 排除数据并且不存在于同一个表中

[英]SQL how to exclude data using datediff and not exists in same table

I'm trying to exclude some data in my query, but wasn't able to figure out myself after searching for keywords.我试图在我的查询中排除一些数据,但在搜索关键字后无法弄清楚自己。

在此处输入图像描述

Above is the example table with columns I have with following query:上面是示例表,其中包含我在以下查询中拥有的列:

SELECT id, date, health, state, reason FROM table1

my goal is excluding (state = START) case and cases when (health = NO && reason = REASON1) if this occurs in 10 minutes after START happen.我的目标是排除 (state = START) 情况和 (health = NO && reason = REASON1) 情况,如果这发生在 START 发生后 10 分钟内。 It's possible to have (health = NO && reason = REASON1) after 10 minutes of START event, and I want to leave them there as is if condition of in 10 minutes doesn't meet.在 START 事件 10 分钟后可能会有 (health = NO && reason = REASON1),如果 10 分钟内的条件不满足,我想将它们留在那里。

Below is the goal I wanted to achieve.下面是我想要达到的目标。

在此处输入图像描述

Excluding (state = START) was very easy:排除 (state = START) 非常简单:

SELECT id, date, health, state, reason FROM table1 WHERE state not in ('START')

but I wasn't able to figure out how to exclude (health = NO && reason = REASON1) if this occurs in 10 minutes after START happen part.但如果这发生在 START 发生部分后 10 分钟内,我无法弄清楚如何排除 (health = NO && reason = REASON1)。

My idea was using DATEDIFF and not exists, like following:我的想法是使用 DATEDIFF 并且不存在,如下所示:

SELECT id, date, health, state, reason FROM table1 WHERE state not in ('START') and (health = 'NO' and reason = 'REASON1' and DATEDIFF(minute,(current_date)?,(last starting time)?) < 15)

(current_date)?,(last starting time)? (current_date)?,(最后开始时间)? parts I'm not sure how to achieve this.部分我不确定如何实现这一点。 I think I should use NOT EXISTS as well for the second condition, but the one I tried didn't work.我想我也应该使用 NOT EXISTS 作为第二种情况,但是我尝试过的那个没有用。 Can anyone help or give me direction to go?任何人都可以帮助或指导我到 go 吗?

If I understand correctly, you can use a window function to calculate the previous start date.如果我理解正确,您可以使用 window function 来计算上一个开始日期。 Then the filtering is pretty easy:然后过滤非常简单:

SELECT id, date, health, state, reason
FROM (SELECT t1.*,
             MAX(CASE WHEN state = 'START' THEN date END) OVER (PARTITION BY id ORDER BY date) as prev_start_date
      FROM table1 t1
     ) t1
WHERE state <> 'START' OR
      (health = 'NO' AND
       reason = 'REASON1' AND
       prev_start_date > date - interval 10 minute
      );

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

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