@mysql查询最大连续天数 sql

SELECT
uid,
min(date) AS mindate,
max(date) AS maxdate,
max(countday) countday,
group_concat(date) dates
FROM(
SELECT uid,date,@countday := ( CASE WHEN ( DATEDIFF(date ,@last_date) = 1) THEN (@countday + 1) ELSE 1 END) AS countday,
@last_date := date
FROM(SELECT uid,dateFROM test_demo ORDER BY uid,date) AS t1,
(select @countday:=0,@last_date:=’’) as t2
) AS t3 GROUP BY uid

SELECT DATEDIFF(‘2015-09-02’,‘2015-09-01’)

分解sql
SELECT uid,dateFROM test_demo ORDER BY uid,date 排序查出id,日期

@countday @last_date 这种是变量声明

:= 赋值

@countday := ( CASE WHEN ( DATEDIFF(date ,@last_date) = 1) THEN (@countday + 1) ELSE 1 END
DATEDIFF(d1,d2) 计算两个时间的时间差值
当两个时间差值为1的时候,则为连续天数,
@countday + 1 变量加一,否则为1 结束

@last_date := date 将data赋值变量@last_date

所以每次比较的都是当前行data和上一行data比较。

(select @countday:=0,@last_date:=’’) as 赋值变量

测试数据
CREATE TABLE test_demo (
id int(11) NOT NULL AUTO_INCREMENT,
uid int(11) NOT NULL DEFAULT ‘0’,
date date NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY idx_ud (uid,date)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1

INSERT INTO test_demo (id, uid, date) VALUES

(1, 1, ‘20111-011-01’),

(2, 1, ‘20111-011-02’),

(17, 1, ‘20111-011-03’),

(18, 1, ‘20111-011-04’),

(3, 2, ‘20111-011-01’),

(40, 2, ‘20111-011-02’),

(118, 2, ‘20111-011-03’),

(20, 2, ‘20111-011-04’),

(11, 3, ‘20111-011-01’),

(6, 3, ‘20111-011-02’),

(21, 3, ‘20111-011-03’),

(22, 3, ‘20111-011-04’),

(75, 4, ‘20111-011-01’),

(87, 4, ‘20111-011-02’),

(101, 11, ‘20111-011-01’),

(10, 11, ‘20111-011-02’),

(11, 6, ‘20111-011-01’),

(12, 6, ‘20111-011-02’),

(13, 7, ‘20111-011-01’),

(94, 7, ‘20111-011-02’),

(18, 8, ‘20111-011-01’),

(156, 8, ‘20111-011-02’);

你可能感兴趣的:(mysql)