Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split single column values into multiple columns based on other column values

Tags:

sql

sql-server

I am trying to split single column values into multiple columns based on another column value, I could get it but I am unable to remove the additional null values I get

table

create table tbl1
(id int, strtype varchar(50), strvalue varchar(20));

insert into tbl1 values
(1, 'name', 'a'),(1, 'value', 'a1'),(1, 'name', 'b'),(1, 'value', 'b1');

Desired output

NAME    VALUE
a       a1
b       b1

sql i tried

select 
(case when strtype='name' then strvalue end) as name,
(case when strtype='value' then strvalue end) as value
from tbl1
like image 816
abdulH Avatar asked Sep 30 '22 11:09

abdulH


2 Answers

Check the below script and hope this help you:

Select t1.strValue , t2.strvalue from tbl1 t1 inner join tbl1 t2 on t1.id = t2.id 
where t1.strtype = 'name' and t2.strtype = 'value' and t1.strvalue = LEFT(t2.strvalue ,1) 
like image 185
Paresh J Avatar answered Oct 02 '22 16:10

Paresh J


If am not wrong this should help you.

SELECT *
FROM   (SELECT *
        FROM   tbl1) a
       PIVOT (Max(strvalue)
             FOR strtype IN (name,value)) pv
UNION
SELECT *
FROM   (SELECT *
        FROM   tbl1) a
       PIVOT (Min(strvalue)
             FOR strtype IN (name,value)) pv 
like image 30
Pரதீப் Avatar answered Oct 02 '22 16:10

Pரதீப்