talha choudhary
talha choudhary

Reputation: 23

How to merge columns in SQL of the same table

I have two date columns. Sometimes they both have dates(Which will be same always in both the columns) and sometimes one is empty and one has date value. So, instead of two columns, I am trying to get one column. If one is empty it will take date value from other column and if both have values(which will always be same) it will just take any of the value from the two columns.

I have tried UNION commands but its not giving me the desired result.

enter image description here

Upvotes: 2

Views: 3473

Answers (5)

Sabin Bajgain
Sabin Bajgain

Reputation: 43

It seems there is no case for both column to be empty, then in such condition, you can do something like this:

 SELECT
       CASE
              WHEN column1 IS NULL THEN column2
              WHEN column2 IS NULL THEN column1
              ELSE column1 orcolumn2 

Upvotes: 0

Chris Albert
Chris Albert

Reputation: 2507

SQL Server has a couple different options for this scenario. You can use COALESCE, ISNULL, or a CASE statement.

Based on the information you provided I would use COALESCE. It offers several benefits over ISNULL and is very simple to implement. A CASE statement seems like overkill for what you are trying to do. Check out the link above for more info on each solution.

Upvotes: 4

Airo
Airo

Reputation: 68

UPDATE tableName
SET Date1Column = ISNULL(Date1Column, Date2Column);

Context: ISNULL ( check_expression , replacement_value ), if first argument is not null, it will use that argument.

After the update, delete the other column.

Upvotes: 0

Andy Vilchez
Andy Vilchez

Reputation: 1

You could use the ISNULL statement if it is SQL

SELECT  ISNULL(ReturnDate,RepartureDate) as dateAct FROM AviationReservation_dev

Upvotes: 0

Brian
Brian

Reputation: 1248

Welcome to Stack Overflow!

You need Coalesce

Also, in the future, you should put sample data and metadata in text in your question, rather than as attachments.

Upvotes: 1

Related Questions