我有兴趣仅保留Microsoft SQL Server查询中在两个不同日期的值超过特定阈值的个人。如果个人两次得分均高于150,并且第二个日期是在第一次约会之后至少7天,那么我想返回其ID,其得分高于150的第二个日期以及第二个日期的分数。
以下是数据:
SubjectID DATE Score
001 01/11/2014 147
001 02/11/2013 151
002 02/10/2015 152
003 08/12/2013 155
002 01/31/2012 159
003 07/19/2016 157
因此,对于结果,我想返回以下内容:
SubjectID DATE Score
002 02/10/2015 152
003 07/19/2016 157
根据我问的上一个问题,我正在使用以下代码返回第二个日期:
SELECT *
FROM Clinic a
WHERE a.score > 150
AND a.date IN (SELECT MAX(b.date)
FROM Clinic b
WHERE b.subjectId = a.subjectId
AND b.score > 150)
我认为我需要在WHERE语句中添加以下内容:
AND (b.date - a.date) > 7;
答案 0 :(得分:2)
只需使用lag()
:
select c.*
from (select c.*, lag(date) over (partition by c.subjectid order by c.date) as prev_date
from clinic c
where c.score > 150
) c
where date > dateadd(day, 7, prev_date);
您也可以使用相关子查询来解决此问题:
select c.*
from clinic c
where c.score > 150 and
c.date > (select dateadd(day, 7, c2.date)
from clinic c2
where c2.subjectid = c.subjectid and c2.score > 150
);
答案 1 :(得分:2)
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
REDIRECT tcp -- anywhere anywhere tcp dpt:http redir ports 8080
REDIRECT tcp -- anywhere anywhere tcp dpt:https redir ports 8443
是必经之路。但以防万一您想完成原始查询:
LAG