【问题标题】:Finding max date if no null value in endDate?如果 endDate 中没有空值,则查找最大日期?
【发布时间】:2013-04-23 09:55:41
【问题描述】:

我的数据库中有以下行。

            profileID |     startDate     |   endDate
   -------------------|-------------------|--------------
    Jr.software eng.  |2012-07-01         |2030-01-01
    ..................|...................|..............
     Eng              |2013-03-28         |2013-03-28
    ..................|...................|..............
     Sr.eng           |2013-04-09         |2013-04-17
    ..................|...................|..............
     CEO              |2012-11-21         |
    ..................|...................|..............

上面的行存储在我的数据库中。我想得到这样的结果。

1. If endDate is null then I get only it related startDate.

就像上面一行我的预期结果是

        profileID  |     startDate     |   endDate
   -------------------|-------------------|--------------
     CEO              |2012-11-21         |
    ..................|...................|..............
  1. 如果没有 null endDate,那么我想从 endDate 列表中获取最大的 endDate。

但是如果行是这样的那么

           profileID  |     startDate     |   endDate
   -------------------|-------------------|--------------
    Jr.software eng.  |2012-07-01         |2030-01-01
    ..................|...................|..............
     Eng              |2013-03-28         |2013-03-28
    ..................|...................|..............
     Sr.eng           |2013-04-09         |2013-04-17

那么我的预期结果是

           profileID  |     startDate     |   endDate
   -------------------|-------------------|--------------
    Jr.software eng.  |2012-07-01         |2030-01-01
    ..................|...................|..............

我需要一个 mysql 查询。

【问题讨论】:

  • 1.请显示使用您迄今为止尝试过的代码。 2. 也许给我们展示一些正确结果的例子。 3.也许设置一个sqlFiddle。
  • 最终希望的结果只有Jr.software eng?为什么只是它?
  • 因为 endDate 值 2030-01-01 之间是最大值。如果 null 值不存在,则需要显示最大 endDate。

标签: mysql sql


【解决方案1】:
Select profileId, Case When endate is NULL then startDate 
       Else Max(EndDate) end  As `Date`
From tablename

【讨论】:

  • 也许你应该以日期结尾
【解决方案2】:
SELECT
    l.profileID,
    IF(l.endDate IS NULL,l.startDate,MAX(endDate)) AS Date
FROM mytable AS l

【讨论】:

    【解决方案3】:

    我猜你正在寻找类似的东西:

     SELECT profileID,startDate,MAX(endDate) AS endDate
     FROM table1 
     group by profileID
    

    DEMO HERE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多