这是我的项目表。它具有两个字段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 |
-------------------------------
答案 0 :(得分:2)
只需使用min
和max
函数
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