Matthew Mahgrefteh
Matthew Mahgrefteh

Reputation: 27

SQL query to combine 2 date columns into a combined column

I have a table with two different data columns that I want to combine into one column l.date_Combined.

First consider if there is a date in l.date_time_ic. If that is empty look for the date in l.date_time_mc. Place the result into l.date_Combined.

I was able to do the where clause but I don't know how to build the update logic for the combined field.

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));

Upvotes: 3

Views: 5767

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269493

I believe you just want coalesce(). More importantly, represent your dates using an ISO/ANSI standard format, such as 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' ;

You will notice that I changed the date logic to use comparisons rather than between. Here is a good blog on that subject. Most of what is in the blog applies to all databases, not just SQL Server.

Upvotes: 3

Related Questions