Share
Pivot a table in SQL without using pivot function
Question
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Suppose there are two columns
Age Name
25 Nitin
30 Amit
27 Rishab
29 Ankush
Convert into
Name Nitin. Amit. Rishab. Ankush
Age. 25. 30. 27. 29
Answers ( 5 )
select ‘age’ as name
, *
from
(
select
max(case when name like ‘Nitin’ then age end) as Nitin
,max(case when name like ‘Amit’ then age end) as Amit
,max(case when name like ‘Rishab’ then age end) as Rishab
,max(case when name like ‘Ankush’ then age end) as Ankush
from
);
select ‘age’ as name
, *
from
(
select
max(case when name like ‘Nitin’ then age end) as Nitin
,max(case when name like ‘Amit’ then age end) as Amit
,max(case when name like ‘Rishab’ then age end) as Rishab
,max(case when name like ‘Ankush’ then age end) as Ankush
from
);
select ‘age’ as name
, *
from
(
select
max(case when name like ‘Nitin’ then age end) as Nitin
,max(case when name like ‘Amit’ then age end) as Amit
,max(case when name like ‘Rishab’ then age end) as Rishab
,max(case when name like ‘Ankush’ then age end) as Ankush
from
);
With CTE As
(SELECT Age, Name, ROW_NUMBER() OVER() As Row_Number
FROM table)
SELECT
MAX(CASE Name WHEN ‘Nitin’ Then Age End) Nitin,
MAX(CASE Name WHEN ‘Amit’ Then Age End) Amit,
MAX(CASE Name WHEN ‘Rishab’ Then Age End) Rishab,
MAX(CASE Name WHEN ‘Ankush’ Then Age End) Ankush
FROM CTE
GROUP BY Row_Number
Paste as Transpose.