Adrian Sandoval
Adrian Sandoval

Reputation: 37

Create third column from 2 columns in SQL Server

How can I show a column where the values from the first column completes the missing values of the second column?

I want this result (red marked column):

select example

Upvotes: 0

Views: 997

Answers (3)

Kannan Kandasamy
Kannan Kandasamy

Reputation: 13959

you can use case as below:

Select *, ThirdColumn = Case when SecondColumn is null then FirstColumn else SecondColumn End
   FourthColumn = Row_Number() over(partition by coalesce(SecondColumn,FirstColumn) order by Id)
   from yourtable

or with coalesce

Select *, ThirdColumn = coalesce(SecondColumn,FirstColumn)
   FourthColumn = Row_Number() over(partition by coalesce(SecondColumn,FirstColumn) order by Id)
   from yourtable

Upvotes: 0

Ilyes
Ilyes

Reputation: 14928

Using CASE:

SELECT COL1 , COL2 , COL3 = CASE WHEN COL1 IS NOT NULL THEN COL1 ELSE COL2 END
FROM YOURTABLE;

Using coalesce :

SELECT * ,coalesce(COL1,COL2) AS COL3
FROM YOURTABLE;

Upvotes: 1

Rachel Ambler
Rachel Ambler

Reputation: 1594

Select Column1, Column2, Coalesce(column2, Column1)

That's assuming ALL you care about is column2 UNLESS there's a value in column1, at which point you want column1.

Your question's not overtly clear.

Upvotes: 3

Related Questions