【问题标题】:How to change columns to rows如何将列更改为行
【发布时间】:2020-08-05 20:35:24
【问题描述】:

我有一个问题。

在 SQL 中,我必须使用带有多个错误代码的声明 ID 对表进行编码。所以显示如下

ClaimID    Error1  Error2  Error3 Error4
1234       300     301     302     303

我希望错误显示在单独的行中,例如

ClaimID  Error
1234     300
1234     301
1234     302
1234     303

如何在 SQL 中编写代码?谢谢

【问题讨论】:

  • 请用您正在运行的数据库标记您的问题:sql-server、postgresql、oracle...?

标签: sql union unpivot


【解决方案1】:

您想要取消透视行到列。最佳解决方案取决于您正在运行的数据库。跨数据库的方法是union all:

select claimID, error1 as error from mytable
union all select claimID, error2 from mytable
union all select claimID, error3 from mytable
union all select claimID, error4 from mytable

在支持横向连接和values() 行构造函数的数据库中,有更好的选择,不需要多次扫描表。

在 Postgres 中:

select x.*
from mytable t
cross join lateral (values 
    (t.claimID, t.error1),
    (t.claimID, t.error2),
    (t.claimID, t.error3),
    (t.claimID, t.error4)
) as x(claimID, error)

在 SQL Server 中,您只需将 cross join lateral 替换为 cross apply

【讨论】:

  • 是SQL服务器
  • @Lissette:我的回答涵盖了这一点。
猜你喜欢
  • 2021-10-10
  • 2018-10-30
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 2013-10-18
相关资源
最近更新 更多