简体   繁体   English

检查值是 SQL 中的第二天还是前一天

[英]Check if a value is the next or previous day in SQL

I'm trying to count how many times the next or previous day of a day has a certain value when that day has a certain value.我正在尝试计算当天的第二天或前一天有多少次具有特定值时该天具有特定值。 (I simplify the database structures to make you understand better what I need) Example: (我简化了数据库结构,让您更好地了解我需要什么)示例:

Date          Event
2015-01-01       x
2015-01-02       x
2015-01-03      rest
2015-01-04      sick
2015-01-05       x
2015-01-06      sick
2015-01-07      rest
2015-01-08       x
2015-01-09       x

I need to count how many days a person is sick after or before the rest day.我需要计算一个人在休息日之后或之前生病的天数。 In this case the result from the query should be: 2在这种情况下,查询的结果应该是:2

You can use a cumulative sum of 'rest' to get groups.您可以使用'rest'的累积总和来获取组。 Then aggregate and filter:然后聚合和过滤:

select count(*)
from (select t.*,
             sum(case when event = 'rest' then 1 else 0 end) over (order by date) as rest_grp
      from t
     ) t
where state = 'sick' 
group by rest_grp;

This actually returns three rows -- because there are three gruops (before the rest, in-between, and after the last).这实际上返回三行——因为有三个组(在其余组之前、中间和最后一组之后)。

If you specifically want the middle group, then use:如果您特别想要中间组,请使用:

where state = 'sick' and rest_grp = 1

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

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