例如,我所拥有的是一张表格如下:
ID varchar2(6)
ERROR_TYPE varchar2(30)
ERROR_CODE varchar2(6)
ERROR_DESCRIPTION varchar2(50)
REVIEWED_FLAG varchar2(1)
ID只是典型的随机ID,ERROR_TYPE是导致错误的功能,例如订单或货件。 REVIEWED_FLAG是' Y'或者' N',ERROR_DESCRIPTION就是这样,而ERROR_CODE是一个代码,如1A或2B,其中:
0 - 它通过/没有错误,或
1 - 失败/出现错误
完整的错误代码看起来像1A = 0,或2B = 1(不是我的选择,这是我给予处理的。)
标准
select ID, ERROR_CODE from ERROR_TABLE where ERROR_TYPE = 'SHIPMENT'
将返回如下结果集:
ID ERROR_CODE ERROR_TYPE
100001 1A=0 SHIPMENT
100001 2B=1 SHIPMENT
100001 3A=1 SHIPMENT
100001 4B=0 SHIPMENT
100002 1A=1 SHIPMENT
100002 2B=1 SHIPMENT
100002 3A=0 SHIPMENT
100002 4B=0 SHIPMENT
用户想要看到的是:
ID ERROR_TYPE ERROR_CODE_1A ERROR_CODE_2B ERROR_CODE_3A ERROR_CODE_4B
1000001 SHIPMENT 0 1 1 0
1000002 SHIPMENT 1 1 0 0
我在PIVOT上看到的是它只适用于聚合函数。这不是串联,因为这些值都在各自的列中。
我最终创建了一个基本上
的视图create view V_SHIPMENT_ERRORS as
with ERROR1A as (select ID, substr(ERROR_CODE, 4) as ERROR_CODE_1A from error_table
where error_type = 'SHIPMENT' and error_code like '1A%'),
with ERROR2B as (select ID, substr(ERROR_CODE, 4) as ERROR_CODE_2B from error_table
where error_type = 'SHIPMENT' and error_code like '2B%'),
with ERROR3A as (select ID, substr(ERROR_CODE, 4) as ERROR_CODE_3A from error_table
where error_type = 'SHIPMENT' and error_code like '3A%'),
with ERROR4B as (select ID, substr(ERROR_CODE, 4) as ERROR_CODE_4B from error_table
where error_type = 'SHIPMENT' and error_code like '4B%')
select a.ID, error_code_1A, error_code_2B, error_code_3A, error_code_4B
from error1a a, error2b b, error3a c, error4b d
where a.id = b.id
and a.id = c.id
and a.id = d.id;
这确实给了我想要的结果集。
基本问题 - 是否有一种更有效的方法,只使用SQL进行行/列操作?
对此的评论是,如果有人希望做同样的事情,我希望我的工作至少可以帮助他们。我无法在任何地方找到这种类型的解决方案,这是多个网站上的想法组合导致了这一点。
答案 0 :(得分:1)
您可以使用条件聚合:
select id, shipment_type,
max(case when error_code like '1A=' then substr(error_code, -1) end) as ec_1a,
max(case when error_code like '2B=' then substr(error_code, -1) end) as ec_2b,
max(case when error_code like '3A=' then substr(error_code, -1) end) as ec_3a,
. . .
from error_table
group by id, shipment_type;