SQL:结合学生记录以反映最新的

时间:2017-09-03 15:05:49

标签: sql

所以我有下表:

+-----------+---------+-----------+--------------+------------+
| studentId | deptId  | level     | startDate    | passDate   |
+-----------+---------+-----------+--------------+------------+
| 1         | Math1   | Freshman  | 01-01-2014   | 01-01-2015 |
+-----------+---------+-----------+--------------+------------+
| 2         | Eng1    | Feshman   | 01-01-2012   | 01-01-2013 |
+-----------+---------+-----------+--------------+------------+
| 1         | Math1   | Sophomore | 01-01-2015   | 01-01-2016 |
+-----------+---------+-----------+--------------+------------+
| 1         | Math1   | Junior    | 01-01-2016   | 01-01-2017 |
+-----------+---------+-----------+--------------+------------+
| 1         | Math1   | Senior    | 01-01-2017   | 05-05-2017 |
+-----------+---------+-----------+--------------+------------+
| 2         | Eng1    | Sophomore | 01-01-2013   | 01-01-2013 |
+-----------+---------+-----------+--------------+------------+
| 2         | Eng1    | Junior    | 01-01-2014   | null       |
+-----------+---------+-----------+--------------+------------+

studentId - 学生ID

deptId - 学生部门ID

level - 学生的常设水平

start - 学生开始参加的日期

passDate - 学生毕业的日期

我想基于passDate组合行,以便将记录滚动到最新日期。我还想将startDate更新到最早的站立日期。 null表示该学生仍然没有从该学位毕业。所以在合并上面的表后,我期待这样的事情:

+-----------+--------+--------+------------+------------+
| studentId | deptId | level  | startDate  | passDate   |
+-----------+--------+--------+------------+------------+
| 1         | Math1  | Senior | 01-01-2014 | 05-05-2017 |
+-----------+--------+--------+------------+------------+
| 2         | Eng1   | Junior | 01-01-2014 | null       |
+-----------+--------+--------+------------+------------+

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT studentId, deptId, level, MIN(startDate) AS startDate, passDate 
FROM (SELECT * FROM your_table
      ORDER BY studentId, startDate DESC) t
GROUP BY studentId;

首先,在子查询中,您对表进行排序,以便每个学生的第一行是具有最新日期的学生。现在,如果您按studentId选择此子查询和分组,则最终会得到每个学生的第一行(即最新记录)。要将startDate更新为最早的站立日期,请选择每个组的最短日期。

您可以在此处尝试查询您的数据:http://sqlfiddle.com/#!9/836b72/6

修改:这是另一个适用于MySQLSQL Server的查询:

SELECT Table1.studentId, deptId, level, minDate AS startDate, passDate 
FROM Table1
INNER JOIN (SELECT studentId, MAX(startDate) AS maxDate, MIN(startDate) AS minDate 
            FROM Table1
            GROUP BY studentId) t ON Table1.startDate = t.maxDate AND Table1.studentId = t.studentId;