如何将行组转置为列

How to transpose groups of rows to columns

我有以下 table 结构:

NAME    SUBJECT  LEVEL      RESULT
Smith   maths    beginner   C
Miller  maths    pro        B
Prince  maths    beginner   F
Smith   physics  pro        B
Miller  physics  pro        B
Prince  physics  beginner   E

我想要某种转置,这样结果看起来像这样:

NAME    LEVEL_maths  RESULT_maths  LEVEL_physics   RESULT_physics
Smith   beginner     C             pro             B
Miller  pro          B             pro             B
...

知道如何使用 (Postgre)SQL 完成此操作吗?任何提示表示赞赏。

试试这个:

select name, 
max(case when subject='maths' then level else end)level_maths,
max(case when subject='maths' then RESULT else end)RESULT_maths,
max(case when subject='physics' then level else end)level_physics,
max(case when subject='physics' then RESULT else end)RESULT_physics
from test
group by name;