Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - columns for different categories

Tags:

sql

sqlite

pivot

I am new to SQL. I have a database with data for different exams, for example:

Student Test Grade
--------------------
St1    T1   A
St2    T1   B
St3    T1   B
St1    T2   B
St2    T2   B
St3    T2   A
St1    T3   A
St2    T3   C
St3    T3   B

Then, I would like to print a report using the Tests (T1, T2 and T3) as columns:

Student  T1   T2   T3
----------------------
St1      A    B    A
St2      B    B    C
St3      B    A    B

I have tried different things, but I got stuck on how to produce such a printout. Any help is appreciated!

like image 624
Michel Mesquita Avatar asked Aug 31 '10 17:08

Michel Mesquita


People also ask

How do you categorize data in SQL?

In SQL, data grouping is performed using a GROUP BY clause. The SQL GROUP BY clause allows us to group individual data based on defined criteria. You can group individual data by one or more table columns.

Can we use multiple GROUP BY in SQL?

We can use the group by multiple column technique to group multiple records into a single record. All the records that have the same values for the respective columns mentioned in the grouping criteria can be grouped as a single column using the group by multiple column technique.

Can I GROUP BY 2 columns?

A GROUP BY clause can contain two or more columns—or, in other words, a grouping can consist of two or more columns.


2 Answers

Use:

  SELECT t.student,
         MAX(CASE WHEN t.test = 'T1' THEN t.grade END) AS T1,
         MAX(CASE WHEN t.test = 'T2' THEN t.grade END) AS T2,
         MAX(CASE WHEN t.test = 'T3' THEN t.grade END) AS T3
    FROM TABLE t
GROUP BY t.student
like image 85
OMG Ponies Avatar answered Sep 29 '22 14:09

OMG Ponies


I asked a similar question a while back. You need something akin to a pivot table, but, that's not available in SQLite (as far as I know).

like image 44
Topher Fangio Avatar answered Sep 29 '22 14:09

Topher Fangio