how to extract or get data from multiple rows in single row by eliminating null values in sql server



Let us consider the below table,

Table Data:



In the above table, we have common fields like Work_Order and unit. Here every time a new record is inserted while inserting TotUnits, ETCUnits, RwUnits. So we need to get them in one row by eliminating null values as we have Work_Order and unit same for three of them as shown below,

OUTPUT:


Here we get data in a single row for every distinct Work_Order and unit.

Query as Follows:

declare @units table
(
    unit varchar(1000)
)
declare @result table
(
    workorder varchar(1000),TotalUnits varchar(1000),ETCUnits varchar(1000),RwUnits varchar(1000),UnitID varchar(1000),Total varchar(1000)
)
insert into @units SELECT distinct Unit FROM  te 

--Cursor for iterating
declare @tableCursor cursor,
        @unit varchar(100)

set @tableCursor = cursor for select * from @units

open @tableCursor
fetch next from @tableCursor into @unit
while(@@fetch_status = 0)
begin

insert into @result

SELECT 
  (SELECT distinct WORK_ORDER as w FROM  te WHERE(unit=@unit)) as workorder,
 (SELECT distinct TotUnits FROM  te WHERE(TotUnits IS NOT NULL and unit=@unit)) as TotalUnits,
  (SELECT distinct ETCUnits FROM  te WHERE(ETCUnits IS NOT NULL and unit=@unit)) as ETCUnits,
  (SELECT distinct RwUnits FROM  te WHERE(RwUnits IS NOT NULL and unit=@unit)) as RwUnits,
   (SELECT distinct unit FROM  te WHERE(unit=@unit)) as UnitID,
   (SELECT distinct STUFF((SELECT ',' +  Total    FROM te   where unit=@unit 
    FOR XML PATH('')), 1, 1, '')  [Total]
    FROM te  where unit=@unit) as Total
 fetch next from @tableCursor into  @unit
end
close @tableCursor
deallocate @tableCursor

select * from @result

Popular posts from this blog

Top MNC Interview Questions- Full Stack Developer

Interview Questions-2

How to get the user details, user current level, next level, Rank in sql server