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!
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.
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.
A GROUP BY clause can contain two or more columns—or, in other words, a grouping can consist of two or more columns.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With