Difference between revisions of "Rows to columns"

From SQLZOO
Jump to: navigation, search
Line 2: Line 2:
 
<div class='ht'>
 
<div class='ht'>
 
<div class=params>schema:scott</div>
 
<div class=params>schema:scott</div>
<source lang=sql class='tidy'>DROP TABLE Exam;
+
<source lang=sql class='tidy'>DROP TABLE exam;
 
DROP TABLE courseGrade;</source>
 
DROP TABLE courseGrade;</source>
 
<source lang=sql class='setup'> CREATE TABLE exam(
 
<source lang=sql class='setup'> CREATE TABLE exam(

Revision as of 09:23, 31 July 2012

Display rows as columns

schema:scott
DROP TABLE exam;
DROP TABLE courseGrade;
 CREATE TABLE exam(
  Student VARCHAR(20),
  Java INTEGER,
  DATABASE 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 myStudents JOIN courseGrade 
 ON (name=student)
GROUP BY name

You can also display columns as rows using:

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')
Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense