PostgreSQL如何将行更改为列

Postgresql how to change row to column

假设我有一个像这样的 table:

type       success    failed
type 1     10         1
type 2     4          0
type 3     5          3

我想用查询

创建一个像这样的table
type     state      count
type 1   success    10
type 1   failed     1
type 2   success    4
type 2   failed     0
type 3   success    5
type 3   failed     3

我应该输入什么查询来显示上面的 table?

使用 colpivot 或交叉表?

你可以尝试使用UNION ALL

查询 1:

SELECT *
FROM (
  SELECT type,'success' state,success count  FROM T
  UNION ALL
  SELECT type,'failed' ,failed  FROM T
) t
ORDER BY type,state desc

Results:

|   type |   state | count |
|--------|---------|-------|
| type 1 | success |    10 |
| type 1 |  failed |     1 |
| type 2 | success |     4 |
| type 2 |  failed |     0 |
| type 3 | success |     5 |
| type 3 |  failed |     3 |

另一种选择是使用 VALUES 子句:

select t.type, u.*
from the_table t
  cross join lateral (  
    values ('success', t.success), ('failed', t.failed)
  ) as u(state,count)
order by t.type, u.state;

Online Example