如何从MYSQL中的日期列表中获取开始年份和结束年份

时间:2018-07-24 07:07:28

标签: mysql

这是我的项目表。它具有两个字段id和project_created_date。我想从project_created_date获取开始年份和结束年份。在这种情况下,开始年份是2016,结束年份是2018。

 -----------------------------------
|   ID  |   PROJECT_CREATED_DATE    |
 -----------------------------------
|   1   |       2018-07-11          |
 -----------------------------------
|   2   |       2018-07-13          |
 -----------------------------------
|   3   |       2018-07-23          |
 -----------------------------------
|   4   |       2016-12-14          |
 -----------------------------------
|   5   |       2017-07-31          |
 -----------------------------------

如果我这样查询,我可以开始和结束年份。

 SELECT year(PROJECT_CREATED_DATE) as startYear FROM `projects` ORDER BY PROJECT_CREATED_DATE ASC LIMIT 1
 SELECT year(PROJECT_CREATED_DATE) as endYear FROM `projects` ORDER BY PROJECT_CREATED_DATE DESC LIMIT 1

但是我想使查询成为单个查询。我的意思是我想得到这样的结果

  ------------------------------
|   startYear   |   endYear     |
 -------------------------------
|       2016    |     2018      |
 -------------------------------

2 个答案:

答案 0 :(得分:2)

只需使用minmax函数

      SELECT min(year(PROJECT_CREATED_DATE)) as  startYear,
        max(year(PROJECT_CREATED_DATE)) as EndYear FROM `projects` 

答案 1 :(得分:1)

使用这样的子选择

SELECT 
(SELECT year(PROJECT_CREATED_DATE) FROM `projects` ORDER BY PROJECT_CREATED_DATE ASC LIMIT 1) as startYear,
(SELECT year(PROJECT_CREATED_DATE) FROM `projects` ORDER BY PROJECT_CREATED_DATE DESC LIMIT 1) as endYear