我敢肯定有一個更好的辦法來做到這一點,但是這是我想出來的。另外,你發佈的問題似乎有點模糊,所以我不完全確定我正確回答了這個問題。
首先,你需要獲得所有可能結果的疏表,然後再加入得到的值。
這具有這樣的輸出作爲數據的單個列。如果沒有使用動態SQL或其他方法創建查詢,則不可能爲每個查詢定製一定數量的列。
SYS_CONNECT_BY_PATH用於數據的多行加入連接成單排。
with table_a as (
select 1 as id, 'nm1' as nm, 1 as enabled from dual union all
select 2 as id, 'nm2' as nm, 1 as enabled from dual union all
select 3 as id, 'nm3' as nm, 0 as enabled from dual union all
select 4 as id, 'nm4' as nm, 1 as enabled from dual
),
table_b as (
select 1 as id, 1 as a_id, 1 as docid, 0.8 as value from dual union all
select 2 as id, 4 as a_id, 1 as docid, 0.6 as value from dual union all
select 3 as id, 1 as a_id, 2 as docid, 0.3 as value from dual union all
select 4 as id, 2 as a_id, 2 as docid, 0.4 as value from dual union all
select 5 as id, 4 as a_id, 2 as docid, 0.7 as value from dual union all
select 6 as id, 2 as a_id, 3 as docid, 0.6 as value from dual union all
select 7 as id, 4 as a_id, 3 as docid, 0.8 as value from dual
),
cartesian_prod as (
select b.docid, a.id, a.nm
from
table_a a
cross join (select distinct docid from table_b) b
where a.enabled = 1
)
select
docid,
ltrim(max(sys_connect_by_path(nm || ' ' || value, ', ')), ', ') as value
from (
select
c.docid,
c.nm,
nvl(to_char(b.value), 'null') as value,
row_number() over (partition by c.docid order by c.id) as rown
from
cartesian_prod c
left outer join table_b b on (b.docid = c.docid and c.id = b.a_id)
)
start with rown = 1
connect by docid = prior docid and rown = prior rown + 1
group by docid
你可以提供一些關於輸出的更多細節嗎?我無法理解它是如何形成的... – Nivas 2010-10-20 14:07:34
我剛剛重新格式化了輸出。我認爲它會更清楚。 – user481779 2010-10-20 14:10:37