需要在多列表中获取第一个日期

时间:2015-08-07 08:02:18

标签: mysql date

我有一个包含多个日期列的表,我需要获取所有列中的第一个日期。我有一个SQL查询来获取列中的所有第一个日期,但是如何在结果中获得第一个日期?我需要的最终结果只是所有列中的第一个/最早的日期。

我的查询:

SELECT
(SELECT EventDate1 FROM 33160_30006_feed WHERE EventDate1 !='' ORDER BY EventDate1 LIMIT 1) AS EventDate_1,
(SELECT EventDate2 FROM 33160_30006_feed WHERE EventDate2 !='' ORDER BY EventDate2 LIMIT 1) AS EventDate_2,
(SELECT EventDate3 FROM 33160_30006_feed WHERE EventDate3 !='' ORDER BY EventDate3 LIMIT 1) AS EventDate_3,
(SELECT EventDate4 FROM 33160_30006_feed WHERE EventDate4 !='' ORDER BY EventDate4 LIMIT 1) AS EventDate_4,
(SELECT EventDate5 FROM 33160_30006_feed WHERE EventDate5 !='' ORDER BY EventDate5 LIMIT 1) AS EventDate_5,
(SELECT EventDate6 FROM 33160_30006_feed WHERE EventDate6 !='' ORDER BY EventDate6 LIMIT 1) AS EventDate_6,
(SELECT EventDate7 FROM 33160_30006_feed WHERE EventDate7 !='' ORDER BY EventDate7 LIMIT 1) AS EventDate_7,
(SELECT EventDate8 FROM 33160_30006_feed WHERE EventDate8 !='' ORDER BY EventDate8 LIMIT 1) AS EventDate_8,
(SELECT EventDate9 FROM 33160_30006_feed WHERE EventDate9 !='' ORDER BY EventDate9 LIMIT 1) AS EventDate_9,
(SELECT EventDate10 FROM 33160_30006_feed WHERE EventDate10 !='' ORDER BY EventDate10 LIMIT 1) AS EventDate_10

我的结果:

EventDate_1|EventDate_2|EventDate_3|EventDate_4|EventDate_5|EventDate_6|EventDate_7|EventDate_8|EventDate_9|EventDate_10|
 2015-06-01| 2015-03-25| 2015-03-27| 2015-03-26| 2015-03-24| 2015-05-08| 2015-03-25| 2015-03-25| 2015-03-29|  2015-03-25

2 个答案:

答案 0 :(得分:2)

您可以尝试GREATESTLEAST

请参阅此问题的other SO posts,看看是否有帮助。

答案 1 :(得分:1)

我会选择日期联合的最小值:

SELECT MIN(AllEventDates.EventDate)
FROM
(
    SELECT EventDate1 AS EventDate FROM 33160_30006_feed
    UNION
    SELECT EventDate2 AS EventDate FROM 33160_30006_feed
    UNION
    SELECT EventDateN AS EventDate FROM 33160_30006_feed
) AS AllEventDates
WHERE AllEventDates.EventDate != ''