sql MySQL的获取连续签到天数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql MySQL的获取连续签到天数相关的知识,希望对你有一定的参考价值。

DROP TABLE IF EXISTS `tab_user_signup`;
CREATE TABLE `tab_user_signup` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `user_signup_time` varchar(20) NOT NULL,
  `goods_id` int(11) NOT NULL,
  `remark` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `goods_id_relative` (`goods_id`),
  CONSTRAINT `goods_id_relative` FOREIGN KEY (`goods_id`) REFERENCES `tab_goods` (`goods_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COMMENT='用户签到表,谁在什么时候,对那个商品进行了签到。';
SELECT
	user_id,
	goods_id,
	max(days) count_days,
	min(login_day) start_date,
	max(login_day) end_date
FROM
	(
		SELECT
			user_id,
			goods_id,
			@cont_day := (
				CASE
				WHEN (
					@last_user_id = user_id
					AND DATEDIFF(login_dt, @last_dt) = 1
				) THEN
					(@cont_day + 1)
				WHEN (
					@last_user_id = user_id
					AND DATEDIFF(login_dt, @last_dt) < 1
				) THEN
					(@cont_day + 0)
				ELSE
					1
				END
			) AS days,
			(
				@cont_ix := (
					@cont_ix +
					IF (@cont_day = 1, 1, 0)
				)
			) AS cont_ix,
			@last_user_id := user_id,
			@last_dt := login_dt login_day
		FROM
			(
				SELECT
					user_id,
					goods_id,
					DATE(user_signup_time) AS login_dt
				FROM
					tab_user_signup
				ORDER BY
					user_id,
					user_signup_time
			) AS t,
			(
				SELECT
					@last_user_id := '',
					@last_dt := '',
					@cont_ix := 0,
					@cont_day := 0
			) AS t1
	) AS t2
GROUP BY
	user_id,
	cont_ix;

以上是关于sql MySQL的获取连续签到天数的主要内容,如果未能解决你的问题,请参考以下文章

laravel 实现每日签到及奖励功能

大厂面试题

sqlserver查询连续签到天数

hive sql之:最大登录天数,获取连续登录指定天数

SQL:连续天数的计算方法

Redis高级数据结构实战(一)BitMap用户连续签到