[英]How to get number of consecutive days from current date using postgres?
I want to get the number of consecutive days from the current date using Postgres SQL我想使用 Postgres SQL 从当前日期获取连续天数
enter image description here在此处输入图像描述
Above is the scenario in which I have highlighted consecutive days count should be like this.以上是我强调的连续天数应该是这样的场景。 Below is the SQL query which I have created but it's not returning the expected result下面是我创建的 SQL 查询,但它没有返回预期的结果
with grouped_dates as (
select user_id, created_at::timestamp::date,
(created_at::timestamp::date - (row_number() over (partition by user_id order by created_at::timestamp::date) || ' days')::interval)::date as grouping_date
from watch_history
)
select * , dense_rank() over (partition by grouping_date order by created_at::timestamp::date) as in_streak
from grouped_dates where user_id = 702
order by created_at::timestamp::date
Can anyone please help me to resolve this issue?谁能帮我解决这个问题?
If anyhow we can able to apply distinct for created_at field to below query then I will get solutions for my issue.如果无论如何我们能够为 created_at 字段应用 distinct 到下面的查询,那么我将为我的问题找到解决方案。
WITH list AS
(
SELECT user_id,
(created_at::timestamp::date - (row_number() over (partition by user_id order by created_at::timestamp::date) || ' days')::interval)::date as next_day
FROM watch_history
)
SELECT user_id, count(*) AS number_of_consecutive_days
FROM list
WHERE next_day IS NOT NULL
GROUP BY user_id
can anyone have idea how to apply distinct to created_at for above mentioned quey?任何人都可以知道如何将 distinct 应用到 created_at 的上述 quey 吗?
To get the "number of consecutive days" for the same user_id:要获取相同 user_id 的“连续天数”:
WITH list AS
(
SELECT user_id
, array_agg(created_at) OVER (PARTITION BY user_id ORDER BY created_at RANGE BETWEEN CURRENT ROW AND '1 day' FOLLOWING) AS consecutive_days
FROM watch_history
)
SELECT user_id, count(DISTINCT d.day) AS number_of_consecutive_days
FROM list
CROSS JOIN LATERAL unnest(consecutive_days) AS d(day)
WHERE array_length(consecutive_days, 1) > 1
GROUP BY user_id
To get the list of "consecutive days" for the same user_id:要获取相同 user_id 的“连续天数”列表:
WITH list AS
(
SELECT user_id
, array_agg(created_at) OVER (PARTITION BY user_id ORDER BY created_at RANGE BETWEEN CURRENT ROW AND '1 day' FOLLOWING) AS consecutive_days
FROM watch_history
)
SELECT user_id
, array_agg(DISTINCT d.day ORDER BY d.day) AS list_of_consecutive_days
FROM list
CROSS JOIN LATERAL unnest(consecutive_days) AS d(day)
WHERE array_length(consecutive_days, 1) > 1
GROUP BY user_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.