I have some tables in MySQL:
+---------+--------------+---------+ +---------+----------+
| TABLE 1 | | TABLE 2 |
+---------+--------------+---------+ +---------+----------+
| id_user | testnumber1 | score | | id_user | username |
+---------+--------------+---------+ +---------+----------+
| 1 | 1 | 90 | | 1 | aaa |
| 1 | 2 | 80 | | 2 | bbb |
| 1 | 3 | 70 | | 3 | ccc |
| 2 | 1 | 60 | +---------+----------+
| 2 | 2 | 66 |
| 2 | 3 | 77 |
| 3 | 1 | 90 |
| 3 | 2 | 80 |
| 3 | 3 | 70 |
+---------+--------------+---------+
Is it possible to get this:
+---------+--------------+--------------+--------------+
| TABLE RESULT |
+---------+--------------+--------------+--------------+
| id_user | testnumber1 | testnumber2 | testnumber3 |
+---------+--------------+--------------+--------------+
| 1 | 90 | 80 | 70 |
| 2 | 60 | 66 | 77 |
| 3 | 90 | 80 | 70 |
+---------+--------------+--------------+--------------+
?
What statement can I use to get this result?
What you need is to
PIVOTthe columns into rows. Unfortunately, MySQL has noPIVOTtable operator. But you can use theCASEexpression to do this, like so:SQL Fiddle Demo