我在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 |
+---------+--------------+---------+
有可能得到这个:
+---------+--------------+--------------+--------------+
| TABLE RESULT |
+---------+--------------+--------------+--------------+
| id_user | testnumber1 | testnumber2 | testnumber3 |
+---------+--------------+--------------+--------------+
| 1 | 90 | 80 | 70 |
| 2 | 60 | 66 | 77 |
| 3 | 90 | 80 | 70 |
+---------+--------------+--------------+--------------+
我可以使用什么声明来获得此结果?
答案 0 :(得分:2)
您需要将PIVOT
列添加到行中。不幸的是,MySQL没有PIVOT
表运算符。但您可以使用CASE
表达式执行此操作,如下所示:
SELECT
id_user,
MAX(CASE WHEN testnumber1 = 1 THEN score END) AS testnumber1,
MAX(CASE WHEN testnumber1 = 2 THEN score END) AS testnumber2,
MAX(CASE WHEN testnumber1 = 3 THEN score END) AS testnumber3
FROM Table
GROUP BY id_user;