MySQL最小连续行

时间:2016-06-23 16:07:18

标签: mysql

我有一个包含数据的表格(按日期排序),如下所示:

   Date    | Country
-----------+---------
2003-01-20 | India
2005-07-14 | France
2005-09-28 | Germany
2006-01-17 | India
2006-10-21 | India
2007-02-08 | France
2008-04-19 | Germany
2010-05-20 | Germany
2012-03-17 | India
2013-05-22 | India
2013-12-31 | India
2014-06-01 | India

要获得一个人在他现在所在的国家工作的月数,我需要获得他所在的最后一个国家报告的最少(最小)日期。在这个例子中,我需要得到2012- 03-17。我尝试了group by和self join,但没有一个正常工作。在此先感谢:)

3 个答案:

答案 0 :(得分:1)

这是一个解决方案。

zenity --info --title="" --text "Choose A or B" --ok-label="B"

答案 1 :(得分:1)

试试这个

select min(date) from table where date > (
select max(date) from table where country!=(
select country FROM table WHERE date= (select max(date) from table)))

答案 2 :(得分:0)

无视我之前的回答,我没有像我应该的那样彻底地阅读你的问题;这应该有效,尽管有些人可能会认为这是对会话变量的边缘滥用。

首先,我们必须确定作业:

SELECT @g := @g + IF(@prevCountry <> t.`Country`, 1, 0) AS assignment, t.`Date`, @prevCountry := t.`Country`
FROM theTable AS t
   , (SELECT @g := 0 AS donotreference1, @prevCountry := null AS donotreference2) AS initSV
ORDER BY `Date`

然后我们需要找到最后一次分配的开始日期:

SELECT a.assignment, MIN(a.`Date`) AS startingDate
FROM ([the query above]) AS a
GROUP BY a.assignment
ORDER BY a.assignment DESC
LIMIT 1
;

您不能在子查询中执行group by,因为它会混淆会话变量的处理方式;在某些情况下,我甚至看到需要将order by放在子子查询中,所以这个

theTable AS t 

可能需要成为

(SELECT `Date`, `Country` FROM theTable ORDER BY `Date`) AS t

已删除原始ORDER BY