【问题标题】:Student absent for 5 consecutive days excluding Holidays学生连续 5 天缺课,节假日除外
【发布时间】:2020-01-24 13:17:41
【问题描述】:

我正在使用如下代码点火器和考勤表:

attendance ID   timestamp   student_id     status
     1           01-01-20        1           P
     2           01-01-20        2           P
     3           02-01-20        1           P
     4           02-01-20        2           A
     5           03-01-20        1           P
     6           03-01-20        2           A
     7           04-01-20        1           H
     8           04-01-20        2           H
     9           05-01-20        1           P
     10          05-01-20        2           A

我的目标是获取从今天开始的最后1个月内连续缺勤3天的学生证,不包括上表中的假期,学生证2应该是连续3天的学生证1 月 4 日假期除外。

我正在使用 Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.6.28 和 mysql。我已经可以连续3次缺席,但是中间有假期,我找不到工作。这是我现有的代码:

SELECT *,
CASE
   WHEN (@studentID  = student_id) THEN @absentRun := IF(status = A, 0, @absentRun + 1)
   WHEN (@studentID := student_id) THEN @absentRun := IF(status = A, @absentRun + 1, 0)
END AS absentRun
FROM attendance
Where timestamp BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE() AND year='2019-2020'
ORDER BY student_id, timestamp;

我真的很感谢有人能快速回答我的问题。我真的很希望有一个解决方案,因为我第一次在这里发帖寻求帮助。提前致谢。

【问题讨论】:

  • 有趣的是,学生 2 在同一天在场、缺席和度假,而在同一天,学生 1 在场并在度假。有量子学生吗?

标签: mysql sql codeigniter mariadb gaps-and-islands


【解决方案1】:

我将其理解为差距和孤岛问题的变体。这是使用row_number()(在 MySQL 8.0 中可用)解决它的一种方法 - 行号之间的差异为您提供每条记录所属的组。

select 
    student_id,
    min(timestamp) timestamp_start,
    max(timestramp) timestamp_end
from (
    select 
        t.*, 
        row_number() over(partition by student_id order by timestamp) rn1,
        row_number() over(partition by student_id, status order by timestamp) rn2
    from mytable t
) t
where status = 2
group by student_id, rn1 - rn2
having count(*) >= 5

这将为您提供每个学生至少连续缺勤 5 天的记录。作为奖励,该查询还显示每个连胜的开始和结束日期。

【讨论】:

  • 因为我是新手。我不小心在最终版之前发布了它。令我惊讶的是,我什至得到了答案。我印象深刻。我必须快点跟上这个。 :)
  • 我试过了,但得到以下错误:发生数据库错误 错误号:1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以获取正确的语法,以便在第 8 行的 '(partition by student_id order by timestamp) rn1, row_number() over(part' at line Number: 189 附近使用
  • @user3734397:您使用的是哪个版本的 MariaDB? Maria DB 10.2.0 中添加了窗口函数。
  • 服务器版本:10.1.19-MariaDB - mariadb.org 二进制分发
  • @user3734397:没有窗口函数,您的问题将更难解决。您应该考虑切换到较新的版本,而不是坚持使用 10.1.... 版本 10.2.0 于 2016 年 4 月发布(实际上早于 10.1019,您正在使用并于 2016 年 11 月发布)。最新的稳定版本是 10.4.11!
猜你喜欢
  • 1970-01-01
  • 2019-05-06
  • 2019-04-10
  • 2017-06-02
  • 2021-09-16
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多