Posts

Showing posts from March, 2020

SQL to pivot columns to rows

-- Create a sample table   create multiset table mydbname.stscorecard (     id integer ,     sname varchar (20),     Math_score integer ,     Science_score integer ,     Social_score integer ) primary index (id) ; insert into mydbname.stscorecard (id,sname,Math_score, Science_score, Social_score) values (1, 'Student1' , 91,92,93) ; insert into mydbname.stscorecard (id,sname,Math_score, Science_score, Social_score) values (2, 'Student2' , 94,95,96) ; -- Following query demonstrates how to pivot a single row into multiple rows -- Assumption here is number of columns to pivot to rows is costant number.   -- In this example as you see we have 3 subjects only. select * from   ( select id,sname, 'Maths' ( varchar (20)) as subject, Math_score as Score   from mydbname.stscorecard union all select id,sname, 'Science' as subject, Science_score as Sc...

SQL to pivot rows to columns

-- Create a sample table   create multiset table mydbname.stscorecard (     id integer ,     sname varchar (20),     subject varchar (20),     score integer ) primary index (id) ; -- Insert sample data for student1 insert into mydbname.stscorecard (id, sname, subject, score) values (1, 'student1' , 'Maths' ,90); insert into mydbname.stscorecard (id, sname, subject, score) values (1, 'student1' , 'Science' ,91); insert into mydbname.stscorecard (id, sname, subject, score) values (1, 'student1' , 'Social' ,99); -- Insert sample data for student2 insert into mydbname.stscorecard (id, sname, subject, score) values (1, 'student2' , 'Maths' ,92); insert into mydbname.stscorecard (id, sname, subject, score) values (1, 'student2' , 'Science' ,93); insert into mydbname.stscorecard (id, sname, subject, score) values (1, 'student2...