如何在不进行动态查询的情况下对字符串进行SQL查询

时间:2019-05-02 11:52:34

标签: sql oracle pivot

我有一张这样的桌子:

ID         CODE
----------------------
1111       HE
1111       HO
1111       FR
2222       CH
2222       AA
2222       LM
2222       BB
3333       HO
3333       FR

我想返回每个id 1行,每行4列

我已经阅读了有关动态SQL的信息,但之前从未使用过。由于定义了列数,因此需要动态查询吗?动态查询也可以在PL / SQL中工作吗?

预期:

ID         CODE_1     CODE_2    CODE_3    CODE_4
--------------------------------------------------
1111       HE         HO        FR        NULL
2222       CH         AA        LM        BB
3333       HO         FR        NULL      NULL

1 个答案:

答案 0 :(得分:1)

如果要特别指定4列-即没有动态增长或收缩的列-您可以执行以下操作:

with
n as (
  select
    id,
    code,
    row_number() over(partition by id order by code) as rn
  from t
)
select
  n0.id,
  n1.code as code_1,
  n2.code as code_2,
  n3.code as code_3,
  n4.code as code_4
from n n0
left join n n1 on n1.id = n0.id and n1.rn = 1
left join n n2 on n2.id = n0.id and n2.rn = 2
left join n n3 on n3.id = n0.id and n3.rn = 3
left join n n4 on n4.id = n0.id and n4.rn = 4
group by id