oracle纵表转横表
遇到不确定字段时采用纵表时,
我们如何查询将他转化为横?
一、创建oracle数据源

如图所示,我们的ziduan为平时横表的某名称(筛选字段值)
我们想把它展示成如图所示的效果该怎么做呢?

二、废话不多说直接贴代码
代码如下(示例):(orcle版本为19,查询字段要加双引号)
1.纵转横
select
"ziduan",
(case "mingcheng" when '年龄' then "valueq" else null end) "age",
(case "mingcheng" when '职位' then "valueq" else null end) "job",
(case "mingcheng" when '性别' then "valueq" else null end) "xingbie"
from "zongbiao";
我们不妨先将它处理为横向展示 如图

2.分组合并处理
代码如下(示例):
select
"ziduan",
listagg("age",'') "age",
listagg("job",'') "job",
listagg("xingbie",'') within group (order by "ziduan") "xingbie"
from
(select
"ziduan",
(case "mingcheng" when '年龄' then "valueq" else null end) "age",
(case "mingcheng" when '职位' then "valueq" else null end) "job",
(case "mingcheng" when '性别' then "valueq" else null end) "xingbie"
from
"zongbiao"
)
group by "ziduan";
得到我们想要的结果如下图所示: 是不是非常好用非常nice

总结
**还有没有更好的方法呢评论区求大神!!**
文章介绍了在Oracle数据库中如何将纵表转换为横表的方法,包括使用CASE语句进行字段转换以及LISTAGG函数进行数据合并。通过示例代码展示了如何处理不确定字段,最后提出了对更优方法的探讨。
532

被折叠的 条评论
为什么被折叠?



