微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL:查找到目前为止连续几天的数量

给定一组带有时间戳字段的记录(代表我的应用程序中的签名),那么确定连续签入的当前条纹的好方法是什么?

换句话说,通过签入时间降序排序的签到,在用户错过一天之前有多少条记录?

目前我正在使用这种技术:

SELECT distinct(uca.created_at::date) as created_at
    FROM user_challenge_activities as uca INNER JOIN user_challenges as uc
    ON user_challenge_id = uc.ID WHERE uc.user_id = #{user.id}
    order by (uca.created_at::date) DESC;

…我将签到时间戳转换为日期(最终以2012-03-20结束),然后在代码中,浏览记录并递增计数器,直到记录与下一记录之间的日期大于1天.

然而,这种方法对我来说似乎很笨拙,而且看起来像Postgres会擅长的那种东西.

那么实际上有更好的方法来实现这一目标吗?

解决方法

with t as (
    SELECT distinct(uca.created_at::date) as created_at
    FROM user_challenge_activities as uca 
    INNER JOIN user_challenges as uc ON user_challenge_id = uc.ID 
    WHERE uc.user_id = #{user.id}
    )
select count(*)
from t
where t.create_at > (
    select d.d
    from generate_series('2010-01-01'::date,CURRENT_DATE,'1 day') d(d)
    left outer join t on t.created_at = d.d::date
    where t.created_at is null
    order by d.d desc
    limit 1
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐