在一个日期列表(或任何列表)上循环,并在mysql或snowflake中附加查询

xj3cbfub  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(276)

我是新的sql语言和最近雪花。我有一个表,其中包含企业所有用户的所有签入日期

user_id | checkin_date
001       03-06-2018
001       07-07-2018
001       08-01-2018
002       03-19-2018
002       03-27-2018
002       07-11-2018

现在我想做一个查询,这样我就可以从查询日期向后看,看看每个用户在查询日期-7和查询日期,查询日期-90和查询日期之间签入了多少次。。。下面的雪花查询正确地完成了查询\u date='2018-08-01'的工作。

with user_checkin_history_sum as (
select 
  user_id,
  sum(iff(datediff(DAY, uc.checkin_date, '2018-08-01') <= 7, 1, 0)) as visits_past_7_days,
  sum(iff(datediff(DAY, uc.checkin_date, '2018-08-01') <= 90, 1, 0)) as visits_past_90_days,
from user_checkin as uc
where uc.checkin_date < '2018-08-01'
group by user_id
order by user_id
)

这给了我结果

user_id | visits_past_7_days | visits_past_90_days
001       0                    2
002       0                    1

我的问题是,如果我有超过一天作为查询日期,也就是说,我有一个签入日期列表,对于列表中的每个签入日期,我按照上面的方式进行查询,并将它们附加在一起。基本上,它是一个loop-over+table-append,但是我没有找到一个在sql语言中如何做到这一点的答案。基本上,我想做的是

with user_checkin_history_sum as (
select 
  user_id,
  sum(iff(datediff(DAY, uc.checkin_date, query_date) <= 7, 1, 0)) as visits_past_7_days,
  sum(iff(datediff(DAY, uc.checkin_date, query_date) <= 90, 1, 0)) as visits_past_90_days,
from user_checkin as uc
where uc.checkin_date < query_date and
LOOP OVER
    query_date in ('2018-08-01', '2018-06-01')
group by user_id
order by user_id
)

希望它能给出这个结果

user_id | query_date | visits_past_7_days | visits_past_90_days
001      '08-01-2018'  0                    2
002      '08-01-2018'  0                    1
001      '06-01-2018'  0                    1
002      '06-01-2018'  0                    2
dy1byipe

dy1byipe1#

您应该能够交叉联接包含要检查的所有日期的表:

WITH dates AS (
    SELECT '2018-06-01' AS query_date UNION ALL
    SELECT '2018-08-01' UNION ALL
    ...     -- maybe other dates as well
),
user_checkin_history_sum AS (
    SELECT
        uc.user_id,
        d.query_date,
        SUM(IFF(DATEDIFF(DAY, uc.checkin_date, d.query_date) <= 7, 1, 0)) AS visits_past_7_days,
        SUM(IFF(DATEDIFF(DAY, uc.checkin_date, d.query_date) <= 90, 1, 0)) AS visits_past_90_days
    FROM dates d
    CROSS JOIN user_checkin AS uc
    WHERE uc.checkin_date < '2018-08-01'
    GROUP BY d.query_date, uc.user_id
    ORDER BY d.query_date, uc.user_id
)

相关问题