Postgresql - 如何对行进行分组并将某些行转换为列

时间:2013-04-14 05:22:13

标签: postgresql rows

我有一个类似于以下内容的数据库:

+------------+-----------+------------+
| student_id |  subject  | test score |
+------------+-----------+------------+
|          3 | math      |         78 |
|          3 | physics   |         66 |
|          3 | english   |         98 |
|          2 | math      |         76 |
|          2 | physics   |         57 |
|          2 | geology   |         87 |
|          2 | english   |         99 |
|          1 | math      |         86 |
|          1 | physics   |         85 |
|          1 | astronomy |         89 |
|          1 | history   |         77 |
+------------+-----------+------------+

我想将subject_ids分组。第二列中的标签将成为列,新行将成为分数。所以看起来应该是这样的:

+------------+------+---------+---------+---------+-----------+
| student_id | math | physics | english | geology | astronomy |
| 1          | 86   | 85      |         |         | 89        |
| 2          | 76   | 57      | 99      | 87      |           |
| 3          | 78   | 66      | 98      |         |           |
+------------+------+---------+---------+---------+-----------+

0 个答案:

没有答案