I have a table StudentMarks
with columns Name, Maths, Science, English
.
Data is like
Name, Maths, Science, English
Tilak, 90
SELECT * FROM student
UNPIVOT(Marks FOR subjects in(Maths , Science , English));
Another way around using cross join would be to specify column names inside cross join
select name, Subject, Marks
from studentmarks
Cross Join (
values (Maths,'Maths'),(Science,'Science'),(English,'English')
) un(Marks, Subject)
where marks is not null;
Your query is very close. You should be able to use the following which includes the subject
in the final select list:
select u.name, u.subject, u.marks
from student s
unpivot
(
marks
for subject in (Maths, Science, English)
) u;
See SQL Fiddle with demo
You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:
remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)
select *
from
(
select name, subject,
case subject
when 'Maths' then maths
when 'Science' then science
when 'English' then english
end as Marks
from studentmarks
Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
)as D
where marks is not null;