从2个日期列中选择所有年份

时间:2017-04-05 07:53:41

标签: mysql

我想要做的事情非常简单,但不确定它是否可行以及我该怎么做?

我有一个mysql数据库,其中有一个表有trackId,StartDate,EndDate,我试图从1个结果集中的两个列中获取所有的distinc年份。

到目前为止,我有这个:

SELECT DISTINCT YEAR(StartDate) as year, YEAR(EndDate) as year 
from TRACK 

我的结果是:

| year | year |
|------|------|
| 2016 | 2017 |
| 2017 | 2018 |

我想要得到的是:

| year |
|------|
| 2016 |
| 2017 |
| 2018 |

它可以吗?

2 个答案:

答案 0 :(得分:0)

使用UNION

SELECT * from (
   SELECT YEAR(StartDate) as year from TRACK 
   UNION
   SELECT YEAR(EndDate) as year from TRACK 
 )
 ORDER BY year

只有在按顺序需要结果时才需要外部选择

答案 1 :(得分:0)

你可以用这个:

SELECT DISTINCT [Year] From
(SELECT StartYear AS [Year] FROM #Test
UNION
SELECT EndYear AS [Year] FROM #Test) A