如何将列更改为行

wtlkbnrh  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(311)

我有个问题。
在sql中,有一个表我必须用一个声明id和多个错误代码来编码。所以它显示如下

ClaimID    Error1  Error2  Error3 Error4
1234       300     301     302     303

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

ClaimID  Error
1234     300
1234     301
1234     302
1234     303

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

qco9c6ql

qco9c6ql1#

您想取消行到列的IVOT。最佳解决方案取决于正在运行的数据库。跨数据库的方法是 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() 行构造函数中,有更好的选项,不需要多次扫描表。
博士后:

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 lateralcross apply .

相关问题