PIVOT的Oracle REGEXP_SUBSTR列名

时间:2014-10-14 11:00:31

标签: sql regex oracle pivot regexp-substr

我在PL/SQL Developer v10数据库上使用Oracle 11g 在我们的系统中,我们有一个问题和答案表,我需要“平坦化”#39;为每个客户回答每个问题。

一组问题在问题描述中具有特定代码(PIFQ),使得以下脚本成为可能。只需UPPER(substr(q.questiondescription,1,6))然后转动可能的代码列表。

 select * from (
                    select
                      tqs.transactiondetailid as transactiondetailid,
                      q.productid as productid,
                      tqs.answer as QAnswer,
                      UPPER(substr(q.questiondescription,1,6)) as QDesc,
                      tqs.transactionversion as transactionversion
                    from TRANSACTIONDETAILQSHIS tqs
                    inner join question q on q.questionid = tqs.questionid and 
                    q.questiondescription like 'PIFQ%'
    ) pivot (
    min(QAnswer) for QDesc in (
    'PIFQ01','PIFQ02','PIFQ03','PIFQ05','PIFQ06','PIFQ07','PIFQ08','PIFQ09','PIFQ10',
    'PIFQ11','PIFQ12','PIFQ13','PIFQ14','PIFQ15','PIFQ16','PIFQ17','PIFQ18','PIFQ19','PIFQ20',
    'PIFQ21','PIFQ22','PIFQ23','PIFQ24','PIFQ25','PIFQ26','PIFQ27','PIFQ28','PIFQ29','PIFQ30',
    'PIFQ31','PIFQ32','PIFQ33','PIFQ34','PIFQ35')
    )

导致TRANSACTIONDETAILQSHIS中回答的所有问题都有一行。

现在其他一组问题有三个不同长度的代码(DT,WIF,WT) 一些例子:

DT01. Are you married?
DT05. Do you have children?
WIF1.1.1 First Name
WIF1.2 Date Of Birth
WIF7.10 How many other properties do you own?
WIF14.3.7 Post Code
WIF15 Notes to solicitor
WT01. Will Type

其中没有任何代码之间有空格并且后面有空格,但问题表中的所有其他代码也是如此。我想在这里使用REGEXP_SUBSTR来提取数据透视代码并使用相同的逻辑来捕获QDesc。我们正在谈论100个问题,所以我宁愿避免列出代码。

我坚持制作正则表达式(这只是选择正确的问题代码的部分,但在我完成它之后 - 它将是一块蛋糕)。 我的ATM是:

select UPPER(REGEXP_SUBSTR(q.questiondescription,'(WIF|DT|WT)\d{1,2}.')) from question q

确实选择了第一组(WIF|DT|WT)

之后的第一个数字
DT01. Are you married?
DT05. Do you have children?
WT01. Will Type

如何使用.捕获具有WIF15且没有它们的逻辑(WIF1.1.1 First Name WIF1.2 Date Of Birth WIF7.10 How many other properties do you own? WIF14.3.7 Post Code WIF15 Notes to solicitor )。

{{1}}

2 个答案:

答案 0 :(得分:3)

这将有效'(WIF|DT|WT)[([:digit:]|.)]*'

SQLFiddle Demo

with my_data(str) as
(
select 'WIF1.1.1 First Name' from dual
union all
select 'WIF1.2 Date Of Birth' from dual
union all
select 'WIF7.10 How many other properties do you own?' from dual
union all
select 'WIF14.3.7 Post Code' from dual
union all
select 'WIF15 Notes to solicitor' from dual
)
select str, regexp_substr(str,'(WIF|DT|WT)[([:digit:]|.)]*') as result from my_data;

<强>结果:

STR                                           RESULT
--------------------------------------------------------
WIF1.1.1 First Name                           WIF1.1.1
WIF1.2 Date Of Birth                          WIF1.2
WIF7.10 How many other properties do you own? WIF7.10
WIF14.3.7 Post Code                           WIF14.3.7
WIF15 Notes to solicitor                      WIF15

答案 1 :(得分:0)

(WIF|DT|WT)\d{1,2}.?

试试这个。选择.可选。

相关问题