如何计算一个用户在MYSQL中连续被标记为橙色的天数?
我想知道如何计算到今天为止,一个用户连续有多少天被标记为橙色。我有以下几点如何计算一个用户在MYSQL中连续被标记为橙色的天数?,mysql,sql,group-by,window-functions,gaps-and-islands,Mysql,Sql,Group By,Window Functions,Gaps And Islands,我想知道如何计算到今天为止,一个用户连续有多少天被标记为橙色。我有以下几点 CREATE TABLE `survey_daily` ( `id` int(11) NOT NULL, `user_id` varchar(30) NOT NULL, `color` varchar(10) NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET
CREATE TABLE `survey_daily` (
`id` int(11) NOT NULL,
`user_id` varchar(30) NOT NULL,
`color` varchar(10) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `survey_daily` (`id`, `user_id`, `color`, `timestamp`) VALUES
(1, '3236', "ORANGE", '2020-05-12 02:40:59'),
(2, '3236', "WHITE", '2020-05-13 02:40:59'),
(3, '3236', "ORANGE", '2020-05-14 02:40:59'),
(4, '3236', "ORANGE", '2020-05-15 02:40:59'),
(5, '3237', "ORANGE", '2020-05-15 02:40:59'),
(6, '3237', "ORANGE", '2020-05-16 02:40:59'),
(7, '3236', "ORANGE", '2020-05-16 02:40:59');
小提琴:
基本上,我在一张表上有多个用户,我想计算一个用户连续被标记为橙色的天数
在我的示例中,用户id 3236应该连续有3天被标记为橙色,而用户3237应该有2天被标记为橙色,直到今天。如果它们今天都没有记录,它将返回0
谢谢这是一个缺口和孤岛问题。如果您正在运行MySQL 8.0,一种方法是使用行数之间的差异来构建用户具有相同颜色的连续记录组,然后聚合:
select
user_id,
count(*) no_records,
min(timestamp) start_timestamp,
max(timestamp) max_timestamp
from (
select
s.*,
row_number() over(partition by user_id order by timestamp) rn1,
row_number() over(partition by user_id, color order by timestamp) rn2
from survey_daily s
) t
where color = 'orange'
group by user_id, rn1 - rn2
order by user_id, start_timestamp
这将为每个用户的每个邻接橙色记录系列生成一条记录:
user_id | no_records | start_timestamp | max_timestamp
:------ | ---------: | :------------------ | :------------------
3236 | 1 | 2020-05-12 02:40:59 | 2020-05-12 02:40:59
3236 | 3 | 2020-05-14 02:40:59 | 2020-05-16 02:40:59
3237 | 2 | 2020-05-15 02:40:59 | 2020-05-16 02:40:59
选择t1.user\u id,MAX1+DATEDIFFt2.`timestamp`,t1.`timestamp`max\u delta
来自调查(u daily t1)
在t1.user\u id=t2.user\u id上加入调查
其中t1.color='橙色'
和t2.color='橙色'
t1.`timestamp`您好,这很好,但我目前运行的是5.6版本的MYSQL。我如何在那个版本中实现这一点您的MySQL版本是什么?5.6,就像小提琴一样,还是最近的?5.6就像我的小提琴一样谢谢我所需要的
select *
from (
select
user_id,
count(*) no_records,
min(timestamp) start_timestamp,
max(timestamp) max_timestamp,
row_number() over(partition by user_id order by count(*) desc) rn
from (
select
s.*,
row_number() over(partition by user_id order by timestamp) rn1,
row_number() over(partition by user_id, color order by timestamp) rn2
from survey_daily s
) t
where color = 'ORANGE'
group by user_id, rn1 - rn2
) t
where rn = 1
order by user_id, start_timestamp
user_id | no_records | start_timestamp | max_timestamp | rn
:------ | ---------: | :------------------ | :------------------ | -:
3236 | 3 | 2020-05-14 02:40:59 | 2020-05-16 02:40:59 | 1
3237 | 2 | 2020-05-15 02:40:59 | 2020-05-16 02:40:59 | 1