【问题标题】:How to find a difference between consecutive rows of a same group?如何找到同一组的连续行之间的差异?
【发布时间】:2020-02-07 16:17:09
【问题描述】:

这个问题是在 Facebook 采访中提出的:

(1) 有两个表

  • 出席人数:日期 |学生ID |出席
  • 学生:student_id |学校ID |等级等级 |出生日期 |家乡

使用这些数据,您能否回答以下问题:

  • 从昨天到今天,哪个年级的出勤率下降幅度最大?

到目前为止,我已经得到了这个,但我被卡住了。你能帮助我吗?谢谢。

(SELECT grade_level, date, COUNT(attendance) AS att FROM attendances AS A
     LEFT JOIN students AS S
     ON A.student_id = S.student_id
     GROUP BY grade_level, date
     HAVING attendance == "yes"
     AND (date == "02-06-2020" OR date == "02-05-2020")
     ORDER BY grade_level, date DESC) AS t

【问题讨论】:

  • 旁白:SQLite3 没有明确的日期类型。为了得到正确的结果,可以将日期定义为YYYY-MM-DD。尽管在您的示例中相等可能有效,但其他操作(例如 betweenorder by)通常不会。

标签: sql sqlite join group-by


【解决方案1】:

您可以加入表格,进行条件聚合,然后排序和限制:

select
    s.grade_level
    sum(a.attendance * case when a.date = date('now') then 1 else -1 end) attendance_drop
from attendances a
inner join students s on s.student_id = a.student_id
where a.date in (date('now'), date('now', '-1 day'))
group by s.grade_level
order by attendance_drop desc
limit 1

【讨论】:

    【解决方案2】:

    请尝试以下脚本,认为它工作正常。

    SELECT TOP 1 s.grade_level, COUNT(a.attendance) AS dropCount 
    FROM students  AS s
    INNER JOIN attendances AS a ON  a.student_id = s.student_id
    WHERE 
        a.attendance = 'no'
        AND (a.date <= DATEADD(DAY,-1, CAST(GETDATE() AS DATE)) AND a.date >= CAST(GETDATE() AS DATE))
    GROUP BY s.grade_level
    ORDER BY dropCount DESC
    

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2014-02-15
      • 2013-07-12
      • 2023-03-19
      相关资源
      最近更新 更多