MySQL根据ID返回最大值和最小值

时间:2018-03-05 15:18:46

标签: mysql

我对关系数据库的经验很少,我正在努力弄清楚我认为是一个相当简单的SQL查询。我正在处理类似于下面的表:

+----+--------+------------+------------+
| id |  type  | start_date |  end_date  |
+----+--------+------------+------------+
|  1 | type_1 | 2010-04-01 | 2011-04-01 |
|  1 | type_1 | 2011-04-02 | 2012-04-02 |
|  2 | type_1 | 2008-04-01 | 2010-04-01 |
|  2 | type_1 | 2010-04-02 | 2015-04-02 |
|  2 | type_1 | 2015-04-03 | 2016-04-03 |
+----+--------+------------+------------+

我正在尝试为表中的每个id返回最早的start_date和最新的end_date,因此结果如下:

+----+--------+------------+------------+
| id |  type  | start_date |  end_date  |
+----+--------+------------+------------+
|  1 | type_1 | 2010-04-01 | 2012-04-02 |
|  2 | type_1 | 2008-04-01 | 2016-04-03 |
+----+--------+------------+------------+

同样,如果这是一个简单的问题,我很抱歉,但数据库不是我的主要责任。非常感谢你的帮助!

2 个答案:

答案 0 :(得分:0)

你可以使用min()max()和group by id

  select id, min(start_date), max(end_date)
  from my_table 
  group by id 

答案 1 :(得分:0)

使用min和max查找子查询中的最早和最晚日期,以便您也可以选择类型。

SELECT tablename.id, type, start, end
FROM 
(
  SELECT id, MIN(start_date) AS start, MAX(end_date) AS end
  FROM tablename
  GROUP BY id 
) a
INNER JOIN tablename on tablename.id = a.id