Sql 计算有条件的一段时间内的人数
我们有一个关于课程中用户信息的表格Sql 计算有条件的一段时间内的人数,sql,postgresql,datetime,count,distinct,Sql,Postgresql,Datetime,Count,Distinct,我们有一个关于课程中用户信息的表格 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
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)
那么我不知道如何计算连续周期。我认为这不是最好的选择。
请帮忙处理你的请求
“成功”学生,当月至少一次在一小时内正确完成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
子查询将筛选当前月份。对于每一行,窗口函数计算同一学生在最后一小时内成功练习的次数。外部查询然后过滤至少一次达到阈值的学生
“成功”学生,当月至少一次在一小时内正确完成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
子查询将筛选当前月份。对于每一行,窗口函数计算同一学生在最后一小时内成功练习的次数。然后外部查询筛选至少一次达到阈值的学生。代码显然是Postgres,因此我删除了SQL Server标记。示例数据和期望的结果也会使您的问题更加清晰。代码显然是Postgres,因此我删除了SQL Server标记。样本数据和期望的结果也会让你的问题更加清晰。