0

我在 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      |
+---------+--------------+--------------+--------------+

?

我可以使用什么语句来得到这个结果?

4

1 回答 1

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;

SQL 小提琴演示

于 2012-11-29T10:32:18.630 回答