我一直在寻找这个时间,我找不到任何相关的东西,所以我会问。我有一个这样的数据库:
id | date | name
1 |2017-01-01 | sarah
2 |2017-01-02 | sarah
3 |2017-01-03 | john
4 |2017-01-04 | john
5 |2017-01-05 | john
6 |2017-01-06 | sarah
7 |2017-01-07 | sarah
8 |2017-01-08 | eddy
9 |2017-01-09 | eddy
我想制作如下列表:
start date | end date | name
2017-01-01 | 2017-01-02 | sarah
2017-01-03 | 2017-01-05 | john
2017-01-06 | 2017-01-07 | sarah
2017-01-08 | 2017-01-09 | eddy
我怎样才能做到这一点?一直在尝试使用:
SELECT MIN(date) as mindate, MAX(date) as maxdate, name
FROM 'table'
GROUP BY name
ORDER BY date DESC
但我得到了这些:
start date | end date | name
2017-01-01 | 2017-01-07 | sarah
2017-01-03 | 2017-01-05 | john
2017-01-08 | 2017-01-09 | eddy
请注意,在我想要的列表中,SARAH这个名字出现了两次,而且在GROUP BY中,Sarah只出现过一次......
答案 0 :(得分:1)
一种选择是使用行号变量来标识每个岛的开始和结束日期。最终结果与您最初的预期结果类似,不同之处在于现在我们将每个岛的开始和结束日期,而不是整个表中的每个名称。
SET @island_number = 0;
SET @name = '';
SELECT MIN(t.date) AS start_date,
MAX(t.date) AS end_date,
t.name
FROM
(
SELECT @island_number:=CASE WHEN @name = name
THEN @island_number
ELSE @island_number + 1
END AS gn,
@name:=name AS name,
date
FROM yourTable
ORDER BY id
) t
GROUP BY t.gn, t.name
答案 1 :(得分:0)
尝试以下查询。
SELECT
MIN(_date) as start_date
,MAX(_date) as end_date
,name_new as name
FROM
(
Select
_date
,if(name = @prev, @seq, @seq := @seq + 1) as seq
,if(name = @prev, name, @prev := name) as name_new
From test, (SELECT @seq := 0, @prev := '') AS init
Order by `_date`
) as der
group by name_new, seq
order by seq