I have a data like:
id maths phy chem
1 50 60 21
2 60 80 22
3 80 90 23
Now I want it to look like:
sub 1 2 3
math 50 60 80
phy 60 80 90
chem 21 22 23
my code:
select *
from mrks
pivot
(
max(maths)
for id in ([1], [2], [3])
) piv
however I'm facing 2 issues
I am not able to transpose chem and phy values
Not able to group maths, phy and chem under subj
In SQL Server, you can unpivot with cross apply, then pivot using conditional aggregation:
select
col,
max(case when id = 1 then val end) col1,
max(case when id = 2 then val end) col2,
max(case when id = 3 then val end) col3
from mytable t
cross apply (values ('maths', maths), ('phy', phy), ('chem', chem)) p(col, val)
group by col
Demo on DB Fiddle:
col | col1 | col2 | col3 :---- | ---: | ---: | ---: chem | 21 | 22 | 23 maths | 50 | 60 | 80 phy | 60 | 80 | 90
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With