Rows to columns

From SQLZoo

Display rows as columns

In this example you are shown how to display your rows as columns, and below you are told how to do the opposite by being able to display columns as rows.

Table 1 displays the results as they are in the database and table 2 displays the results as how they should look when rows have been swapped with columns.

Table 1
studentcoursegrade
Gao CongJava80
Gao CongDatabase77
Gao CongAlgebra50
Dongyan ZhouJava62
Dongyan ZhouDatabase95
Dongyan ZhouAlgebra62
Table 2
namejavaDBAlgebra
Gao Cong807750
Dongyan Zhou629562
schema:scott
DROP TABLE exam;
DROP TABLE courseGrade;
CREATE TABLE exam (
  name VARCHAR(20),
  Java INTEGER,
  dbt INTEGER,
  Algebra INTEGER );
INSERT INTO exam VALUES ('Gao Cong',80,77,50);
INSERT INTO exam VALUES ('Dongyan Zhou',62,95,62);
CREATE TABLE courseGrade (
  student VARCHAR(20),
  course VARCHAR(20),
  grade INTEGER );
INSERT INTO courseGrade VALUES ('Gao Cong','Java',80);
INSERT INTO courseGrade VALUES ('Gao Cong','Database',77);
INSERT INTO courseGrade VALUES ('Gao Cong','Algebra',50);
INSERT INTO courseGrade VALUES ('Dongyan Zhou','Java',62);
INSERT INTO courseGrade VALUES ('Dongyan Zhou','Database',95);
INSERT INTO courseGrade VALUES ('Dongyan Zhou','Algebra',62);

To swap rows into columns you could use either a self join(in the example) or you can use CASE

SELECT name,
       MAX (CASE WHEN course='Java'
        THEN grade ELSE NULL END) AS Java,
       MAX(CASE WHEN course='Database'
         THEN grade ELSE NULL END) AS Database,
       MAX(CASE WHEN course='Algebra'
         THEN grade ELSE NULL END) AS Algebra
  FROM exam JOIN courseGrade 
         ON (name=student)
  GROUP BY name

You can also do the opposite of this by displaying columns as rows.

To do this you use a process that is the opposite of the swapping rows to columns one. The coding for this process is:

SELECT student, 'Java', Java FROM exam
 UNION SELECT student, 'Database', Database 
  FROM exam
  UNION SELECT student, 'Algebra', Algebra 
   FROM exam
SELECT name, java.grade AS java,
db.grade AS DB, alg.grade AS Algebra
  FROM exam
  LEFT OUTER JOIN courseGrade java ON
 (name=java.student AND java.course='Java')
  LEFT OUTER JOIN courseGrade db ON
 (name=db.student AND db.course='Database')
  LEFT OUTER JOIN courseGrade alg ON
 (name=alg.student AND alg.course='Algebra')
DataWars, Data Science Practice Projects - LogoDataWars: Practice Data Science/Analysis with +100 Real Life Projects
  • Your server today is: Dipsy