0

在 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   |

我怎么知道 john 是团队成员:

       | 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 子句中放什么来实现这一点..我只需要知道团队名称、他在该团队中的开始日期以及该团队的结束日期..级别列并不重要..

4

2 回答 2

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

于 2013-07-18T03:17:30.010 回答
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

演示:SQL 小提琴

于 2013-07-18T03:57:03.093 回答