我有一个简单的日志表:
id | user_id | value | created_at | updated_at
假设用户在一个月内进行了多次输入。其中一些条目是连续几天。即周一,周二,周三,周四,但随后她会跳过一天并且不会进入另一个条目,直到坐下。我希望能够说她已经连续4天登录了。我不想在服务器端执行此操作,因为这个表很容易就是数百万个日志条目,所以我开始寻找查询数据库的方法。
经过几个小时,我觉得sequelize并没有很好地处理这个问题,转向原始的sql。我发现,这不是我自己的,这个问题:
WITH
-- This table contains all the distinct date
-- instances in the data set
dates(date) AS (
SELECT DISTINCT CAST(created_at AS DATE)
FROM plan_activity_logs
WHERE user_id = ${user}
),
-- Generate "groups" of dates by subtracting the
-- date's row number (no gaps) from the date itself
-- (with potential gaps). Whenever there is a gap,
-- there will be a new group
groups AS (
SELECT
ROW_NUMBER() OVER (ORDER BY date) AS rn,
dateadd(day, -ROW_NUMBER() OVER (ORDER BY date), date) AS grp,
date
FROM dates
)
SELECT
COUNT(*) AS consecutiveDates,
MIN(date) AS minDate,
MAX(date) AS maxDate
FROM groups
GROUP BY grp
ORDER BY 1 DESC, 2 DESC
如果我正确地理解它,那就完全符合我的要求,但是当它被执行时,sequelize会抛出一个错误:
"sqlMessage": "You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server
version for the right syntax to use near
'dates(date) AS (
SELECT DISTINCT CAST(created_at AS DATE)
' at line 1",
我不太了解sql,但我很确定with语句没有错,所以我想知道这是不是一个sequelize的怪癖我不理解?