【问题标题】:Count the number of people for a period with a condition统计有条件的一段时间的人数
【发布时间】:2021-02-13 20:20:03
【问题描述】:

我们有一张包含课程中用户信息的表格。

CREATE TABLE public.students
(
    student_id integer NOT NULL DEFAULT nextval('students_student_id_seq'::regclass),
    timest timestamp without time zone NOT NULL   ##
    is_correct BOOLEAN NOT NULL,
    CONSTRAINT students_pkey PRIMARY KEY (student_id)
)

一个“成功”的学生,在本月至少有一次在一小时内正确完成了 10 次练习。 帮助查询有关 2020 年 10 月成功学生人数的信息。

试图找出一个小时内连续解决的练习数。为此,我计算了交换和减去 3600。

WITH timediff AS (
     SELECT *,
         LEAD(timest) OVER w AS next_time,
         LEAD(timest) OVER w - timest AS diff
     FROM payment
     WHERE is_correct IS TRUE
     WINDOW w AS (PARTITION  BY student_id ORDER BY timest 
     ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING))

SELECT *,
    CASE  
    WHEN (sum(diff) OVER q) > '3600' 
    THEN diff 
    ELSE (sum(diff) OWER q) 
    END cum_sum
FROM timediff
WINDOW q AS (PARTITION  by student_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

那我不知道如何计算连续周期。我认为这不是最好的选择。 请帮助您的请求。

【问题讨论】:

  • 代码显然是 Postgres,所以我删除了 SQL Server 标记。样本数据和期望的结果也会让您的问题更加清晰。

标签: sql postgresql datetime count distinct


【解决方案1】:

一个“成功”的学生,在本月至少有一次在一小时内正确完成了 10 次练习。

如果我没听错的话,你可以使用窗口函数和范围框:

select count(distinct student_id) cnt_successful_students
from (
    select s.*,
        count(*) filter(where is_correct) over(
            partition by student_id 
            order by timest
            range between interval '1 hour' preceding and current row
        ) cnt
    from students s
    where timest >= date_trunc('month', current_date) 
      and timest <  date_trunc('month', current_date) + interval '1 month'
) s
where cnt >= 10

子查询过滤当前月份。对于每一行,窗口函数计算同一学生在过去一小时内完成了多少次成功练习。然后,外部查询过滤至少达到阈值一次的学生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多