Gajanan
Gajanan

Reputation: 45

How can we get records in single row in SQL server using SQL/TSQL

-- Source

Create table staging
(id int,
 name varchar(50),
 empid int,
 company_id int,
 addres varchar(50)
)

Create table Destination
(id int,
 name varchar(50),
 empid int,
 company_id int,
 addres varchar(50)
)

insert into staging
select 1, 'amit',NULL,101,'USA'
UNION ALL
Select 1,'amit',10002,'','USA'
UNION ALL
Select 2,'Vijay','',650,'China'
UNION ALL
Select 2,'Vijay','','','China'
UNION ALL
Select 5,'Sanjay',589756,NULL,'India'
UNION ALL
Select 5,'Sanjay',NULL,151215,'India'


Select * from staging

-- Expected result

-- Destination table

id  name    empid   company_id  addres
1   amit    10002   101         USA
2   Vijay   0       650         China
5   Sanjay  589756  151215      India

Upvotes: 0

Views: 56

Answers (1)

Mahedi Sabuj
Mahedi Sabuj

Reputation: 2944

Use Group By and MAX

insert into destination
select id, max(name), max(empid), max(company_id), max(addres) from staging
group by id

Result:

enter image description here

Upvotes: 1

Related Questions