将2个日期列合并为一个列的SQL查询

3

我有一个表格,其中有两个不同的数据列,我想将它们合并到一列l.date_Combined中。

首先考虑l.date_time_ic是否有日期。如果为空,请查找l.date_time_mc中的日期。将结果放入l.date_Combined中。

我已经能够做where子句,但我不知道如何构建合并字段的更新逻辑。

select
    l.id,
    l.date_time_ic,
    l.date_time_mc
from 
    new.customers l
where
    ((l.date_time_ic between '4/1/2018' and '4/30/2018') or
    (l.date_time_mc between '4/1/2018' and '4/30/2018' and
     l.date_time_ic is null));

感谢您的第一个问题,马特! 您需要使用SQL“更新”而不是选择。请尝试W3Schools的“更新”文章开始:https://www.w3schools.com/sql/sql_update.asp - M. K. Hunter
当你更好地了解更新的工作方式时,可以调整你提供的查询示例,社区会给你更好的帮助。 - M. K. Hunter
只是补充一下,使用ISNULL/COALESCE函数可能会对你有所帮助。 - Rajat Jaiswal
@M.K.Hunter - 我想避免使用Update。 - Matthew Mahgrefteh
@RajatJaiswal,使用Case语句怎么样?我不知道ISNULL/COALESCE。谢谢。我会研究一下的。 - Matthew Mahgrefteh
@Matt 你也可以使用case语句。虽然ISNULL和COALESCE语法非常简单,但我相信你很快就能看到并实现它。祝你好运。RJ - Rajat Jaiswal
1个回答

3

我认为你只需要使用 coalesce() 函数。更重要的是,使用 ISO/ANSI 标准格式来表示你的日期,例如 YYYY-MM-DD:

select l.id,
       coalesce(l.date_time_ic, l.date_time_mc) as thedate
from new.customers l
where coalesce(l.date_time_ic, l.date_time_mc) >= '2018-04-01' and
      coalesce(l.date_time_ic, l.date_time_mc) < '2018-05-01' ;

您会注意到,我更改了日期逻辑,使用比较而不是between这篇博客对此有很好的解释。大部分内容适用于所有数据库,而不仅仅是SQL Server。

我会尝试这个。感谢你。 - Matthew Mahgrefteh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接