统计一段时间内有条件的人数
Count the number of people for a period with a condition
我们有一个 table 包含课程中用户的信息。
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)
)
一名 'successful' 学生在当月至少有一次在一小时内正确完成了 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)
那我就不知道怎么算连续的经期了。我认为这不是最好的选择。
请帮助处理您的请求。
A 'successful' student who at least once in the current month correctly done 10 exercises in an hour.
如果我没听错,你可以使用 window 函数和范围框:
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
当前月份的子查询过滤器。对于每一行,window 函数计算同一学生在过去一小时内进行了多少次成功的练习。然后外部查询过滤至少达到阈值一次的学生。
我们有一个 table 包含课程中用户的信息。
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)
)
一名 'successful' 学生在当月至少有一次在一小时内正确完成了 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)
那我就不知道怎么算连续的经期了。我认为这不是最好的选择。 请帮助处理您的请求。
A 'successful' student who at least once in the current month correctly done 10 exercises in an hour.
如果我没听错,你可以使用 window 函数和范围框:
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
当前月份的子查询过滤器。对于每一行,window 函数计算同一学生在过去一小时内进行了多少次成功的练习。然后外部查询过滤至少达到阈值一次的学生。