我正在建立一个系统来显示学生们连续两天缺课的情况。例如,此表包含缺勤。
day | id | missed
----------------------------------
2016-10-6 | 1 | true
2016-10-6 | 2 | true
2016-10-6 | 3 | false
2016-10-7 | 1 | true
2016-10-7 | 2 | false
2016-10-7 | 3 | true
2016-10-10 | 1 | false
2016-10-10 | 2 | true
2016-10-10 | 3 | true( 2016-10-8天和2016-10-9天是周末)
在上述情况下:
查询只应选择学生1和3。
仅仅使用一个SQL查询就可以这样做吗?
发布于 2016-02-15 21:45:01
使用内部联接将表的两个实例连接起来--一个与“第一天”连接,另一个与“第二天”连接,然后只需查找两种情况都被遗漏的行:
select a.id from yourTable as a inner join yourTable as b
on a.id = b.id and a.day = b.day-1
where a.missed = true and b.missed = true编辑
既然你改变了规矩..。把它写成日期而不是整篇文章,这就是我要做的:
发布于 2016-02-15 21:49:03
与其他答案相似,但语法不同
select distinct id
from t
where
missed=true and
exists (
select day
from t as t2
where t.id=t2.id and t.day+1=t2.day and t2.missed=true
)发布于 2016-02-15 21:45:14
这将给出它发生的每一个实例。如果连续3天或更长时间错过,您将得到多个点击,所以如果这是一个问题,那么您将需要改进它。
SELECT
T1.id,
T1.day
FROM
My_Table T1
INNER JOIN My_Table T2 ON
T2.id = T1.id AND
T2.day = T1.day + 1 AND
T2.missed = true
WHERE
T1.missed = truehttps://stackoverflow.com/questions/35419581
复制相似问题