您的位置:首页 > 数据库 > Oracle

Oracle查询多个字段行转列处理实践案例

2016-03-21 14:25 405 查看
对于主、从表数据结构,存在显示主表数据时,同时在此行数据中显示子表多行数据,简单的说就是行转列。

在流程应用中,由于会签环节存在多人同时处在待办的情况,这样,查询流程运行情况时,有单行同时显示多行待办记录的情况。

对于此需求,可以在oracle中使用wm_concat函数进行行转列处理。

select wm_concat(t.task_receiver_id) receiver_id,wm_concat(t.task_receiver) receiver,
wm_concat(to_char(t.create_datetime,'yyyy-mm-dd HH24:MI:ss')) start_datetime
from pnd_task t
where t.biz_instanceid = '5724c50c-14b8-11e5-fcce-bbabd873dbe0'


上述代码存在缺陷,三个字段不按顺序排列。

通过把查询目标字段并(用引号里的操作符“||”)在一起的方式,并且,中间用逗号分隔,修改sql代码如下:

select tt.* ,t.* from biz_info_instance tt,
(select t.biz_instanceid biz_instanceid ,wm_concat(t.task_receiver_id||','||t.task_receiver||','||to_char(t.create_datetime,'yyyy-mm-dd HH24:MI:ss'))
from pnd_task t group by t.biz_instanceid ) t
where t.biz_instanceid = tt.biz_instanceid and
tt.mongo_bo_id = '56e0f3cf84ae13d64998a26d'


另一种方式:

select tt.* ,(select wm_concat(t.task_receiver_id||','||t.task_receiver||','||to_char(t.create_datetime,'yyyy-mm-dd HH24:MI:ss'))
from pnd_task t where t.biz_instanceid = tt.biz_instanceid group by t.biz_instanceid )
from biz_info_instance tt
where
tt.mongo_bo_id = '56e0f3cf84ae13d64998a26d'


1、查询业务实例处理情况:

select tt.biz_instanceid,tt.status,tt.create_id,tt.create_name,tt.start_date,tt.end_date ,(select wm_concat(t.task_receiver_id||','||t.task_receiver||','||to_char(t.create_datetime,'yyyy-mm-dd HH24:MI:ss'))
from pnd_task t where t.biz_instanceid = tt.biz_instanceid group by t.biz_instanceid )  task_receiver
from biz_info_instance tt


查询结果如下:



2、查询查询未完成流程实例,有待办的的情况:

select tt.biz_instanceid,tt.status,tt.create_id,tt.create_name,tt.start_date,tt.end_date ,(select wm_concat(t.task_receiver_id||','||t.task_receiver||','||to_char(t.create_datetime,'yyyy-mm-dd HH24:MI:ss'))
from pnd_task t where t.biz_instanceid = tt.biz_instanceid and t.status = 0 group by t.biz_instanceid )  task_receiver
from biz_info_instance tt
// 如果按文档ID条件查询,补充如下语句内容:
where t.mongo_bo_id in ('文档ID','文档IDn')


参考:

Oracle行转列、列转行的Sql语句总结》 2015.01 X-rapido的专栏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  oracle sql 行转列