【问题标题】:In SQL Server, how do I get the latest dates with multiple columns of dates?在 SQL Server 中,如何获取具有多列日期的最新日期?
【发布时间】:2015-12-21 21:41:26
【问题描述】:

这感觉应该很容易。如何获取不同列中的 3 个日期中的最新日期

DROP TABLE #dates
CREATE TABLE #dates (mykey CHAR(10), date1 DATETIME, date2 DATETIME, date3 DATETIME)
INSERT #dates VALUES ('Key1', '1/1/2015', '2/1/2015', '3/1/2105')
INSERT #dates VALUES ('Key2', '1/2/2015', '4/2/2015', '3/2/2105')
INSERT #dates VALUES ('Key3', '1/3/2016', '4/3/2015', '3/3/2105')

select mykey, ?? AS 'Latest Date' from #dates

我希望结果是:

mykey       Latest Date
Key1        2105-03-01 00:00:00.000
Key2        2015-04-02 00:00:00.000
Key3        2016-01-03 00:00:00.000

【问题讨论】:

  • 您可以使用基于UNION ALL/VALUES 多列的派生表中的MAX 轻松实现
  • 我重新打开了这个问题,因为我认为下面的答案比引用的重复问题更好。
  • date3 也应该在 2015 年,而不是 2105 年才能获得您想要的结果,否则它将为所有键返回 date3
  • 理想情况下,修复您的数据模型。相同“类型”的所有数据(以便将两个值相互比较是有意义的)应该在一个列中。当您为列编号时,通常表明数据已嵌入元数据中(即 1、2 和 3有意义,但无法编写使用这些数字的直接查询)或者您有任意限制(为什么停在3?)

标签: sql sql-server datetime


【解决方案1】:

可能在 SQL Server 中最简单的方法是使用cross apply

select d.*, m.maxdate
from #dates d cross apply
     (select max(dte) as maxdate
      from (values (date1), (date2), (date3)) as v(dte)
     )  m;

【讨论】:

  • 即使是很好的查询,它也没有给出输出中提到的准确结果
  • @mohan111 。 . .根据问题的上下文,大概 2105 年是样本数据中的错字。这是一个 SQL Fiddle:sqlfiddle.com/#!6/a52e6/2.
  • 不,我们需要为 key3 获取 2016 年,但在您的查询中,它显示了我们需要的其他值,MAX 表示最高日期
  • @mohan111 。 . .如果我更改第三列中的年份,它会返回 2016:sqlfiddle.com/#!6/09613/1
【解决方案2】:

使用CASE 语句可以完成工作。

DECLARE @dates TABLE (mykey CHAR(10), date1 DATETIME, date2 DATETIME, date3 DATETIME)
INSERT @dates VALUES ('Key1', '1/1/2015', '2/1/2015', '3/1/2105')
INSERT @dates  VALUES ('Key2', '1/2/2015', '4/2/2015', '3/2/2105')
INSERT @dates  VALUES ('Key3', '1/3/2016', '4/3/2015', '3/3/2105')

select mykey, 
case when date1 >= date2 and date1 >= date3 THEN date1
    when date2 >= date1 and date2 >= date3 then date2
    else date3 end [LatestDate]
 from @dates

【讨论】:

    【解决方案3】:

    这里我们可以使用iif声明:

    SELECT mykey
        ,iif(month(date1) > month(date2), iif(month(date1) > month(date3), date1, date3), iif(month(date2) > month(date3), date2, date3)) AS result
    FROM #dates  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 2012-02-26
      相关资源
      最近更新 更多