MySQL从表中选择日期范围,其中只有一列用于日期

时间:2013-07-18 03:06:28

标签: mysql sql

在MySQL数据库中拥有此记录:


 emp_name |   team   |  start date   | level |
----------+----------+---------------+--------
john      |  alpha   |  2013-may-28  |   1   |
john      |  beta    |  2013-apr-05  |   3   |
john      |  beta    |  2013-jan-03  |   1   |
john      |  gamma   |  2012-dec-04  |   3   |
john      |  gamma   |  2012-sep-28  |   2   |
john      |  gamma   |  2012-sep-11  |   1   |
john      |  beta    |  2012-jul-17  |   3   |
john      |  beta    |  2012-may-03  |   1   |
john      |  alpha   |  2012-feb-12  |   3   |
john      |  alpha   |  2012-jan-01  |   1   |

我怎么知道约翰是团队成员:

       | from        | to
 ---------------------------------
 alpha | 2012-jan-01 | 2012-may-03
 beta  | 2012-may-03 | 2012-sep-11
 gamma | 2012-sep-11 | 2013-jan-03
 beta  | 2013-jan-03 | 2013-may-28
 alpha | 2013-may-28 | now

我不知道在我的WHERE子句中要放什么来实现这个...我只需要拥有团队名称,他在该团队上开始的日期,以及该团队的结束日期...等级列中没有重要..

2 个答案:

答案 0 :(得分:1)

SELECT emp_name,min(startdate) as startdate,max(ldate) as enddate,team
FROM (
  SELECT emp_name,startdate ,team,
  @n:=if(@lastteam=team,@n,@n+1) rank,
  @l:=if(@enddate=startdate,startdate,@enddate) ldate,
  @lastteam:=team, @enddate:=startdate 
    FROM t, (SELECT @n := 0,@lastteam:='',@enddate:='') n
    ORDER BY startdate desc
  ) m
GROUP BY rank

SQL FIDDLE:http://www.sqlfiddle.com/#!2/860fd/20

答案 1 :(得分:1)

SELECT emp_name, team, min(start_date) start_date, end_date
  FROM (
    SELECT t1.emp_name, t1.team, t1.start_date, min(t2.start_date) end_date
      FROM table1 t1
 LEFT JOIN table1 t2
        ON t1.emp_name = t2.emp_name
       AND t1.team != t2.team
       AND t1.start_date < t2.start_date
  GROUP BY t1.emp_name, t1.team, t1.start_date) t3
GROUP BY emp_name, team, end_date
ORDER BY start_date

Demo: SQL Fiddle