【问题标题】:Postgresql how to change row to columnPostgresql如何将行更改为列
【发布时间】:2021-10-10 02:12:54
【问题描述】:

假设我有一张这样的桌子:

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

我想用查询创建一个这样的表

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

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

使用 colpivot 或交叉表?

【问题讨论】:

  • 问题 Stilla 说“我想创建一个表格”你可能想要编辑它
  • 你试过什么?您当前的查询是否显示任何错误?

标签: sql postgresql unpivot


【解决方案1】:

你可以尝试使用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 |

【讨论】:

    【解决方案2】:

    另一种选择是使用 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

    【讨论】:

    • @SYAHRILASIDIQFIRDAUS 。 . .这绝对是更好的解决方案,我认为它应该被接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多