sql - 检查一个值是 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
解决方案
您可以使用的累积总和'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
推荐阅读
- list - 在图形的cpp实现中,节点应该存储在模板向量还是列表中?
- android - 默认启动器已设置,但不适用于其他用户
- c# - C# 空 WebClient 下载字符串
- nativescript - Nativescript 图像区域协调点击事件,如 HTML Image Map
- php - 如何使用 USB 令牌使用 PHP 和 chrome 令牌签名扩展在 pdf 中应用数字签名?
- javascript - Calling Javascript function from external file when loading html page
- c# - 使用 datatable() 计算 C# 表单文本框字符串
- csv - PySpark:如何用逗号指定列作为十进制
- android - Android - 模拟问题
- javascript - 我想知道这个函数到底做了什么 .split(' ').map(x => +x);