首页 > 解决方案 > 检查一个值是 SQL 中的第二天还是前一天

问题描述

我试图计算当天有多少次或前一天具有某个值时该天具有某个值。(我简化了数据库结构以使您更好地理解我需要什么)示例:

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

我需要计算一个人在休息日之后或之前生病了多少天。在这种情况下,查询的结果应该是:2

标签: sqlsql-serverdatabase

解决方案


您可以使用的累积总和'rest'来获取组。然后聚合和过滤:

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;

这实际上返回三行——因为有三个组(在其余组之前、中间和最后一个之后)。

如果您特别想要中间组,请使用:

where state = 'sick' and rest_grp = 1

推荐阅读