2016-10-06 21 views
1

我有一個表requesttool.request_detail它用於存儲由REQUEST_ID列中的值標識的實體的屬性。表requesttool.request_detail有一個名爲ATTRIBUTE_ID的列,它指示存儲在稱爲ATTRIBUTE_VALUE的另一列的各行中的內容。例如,如果給定行的ATTRIBUTE_ID ='259',則名稱將存儲在ATTRIBUTE_VALUE的相應行中。選擇獨立的行並將它們顯示爲單行(ORACLE SQL)

這裏是requesttool.request_detail看起來就像在實踐中:

enter image description here

我想要做的是提取存儲在ATTRIBUTE_VALUE 3種不同的ATTRIBUTE_ID的和給定REQUEST_ID的價值,說4500161635,並在一個單行顯示它們,就像這樣:

enter image description here

我曾嘗試在F ollowing代碼:

select 
    request_id, 
    case when attribute_id = '289' then attribute_value end as name, 
    case when attribute_id = '259' then attribute_value end as country, 
    case when attribute_id = '351' then attribute_value end as priority 
from (
    select a.request_id, a.attribute_id, a.attribute_value 
    from requesttool.request_detail a 
    where a.request_id='4500161635'); 

但是從這個我獲得一張桌子空值,不是單行線:

enter image description here

+0

可以羣,然後選擇最高(案例..)對所有3列。 – Kobi

回答

1

你是在正確的軌道上。只有你必須收集您行,以便得到每REQUEST_ID一行結果:

select 
    request_id, 
    max(case when attribute_id = '289' then attribute_value end) as name, 
    max(case when attribute_id = '259' then attribute_value end) as country, 
    max(case when attribute_id = '351' then attribute_value end) as priority 
from requesttool.request_detail 
where request_id = '4500161635' 
group by request_id; 

鑑於REQUEST_ID + attribute_id索引,你也許可以通過增加一個條件,你的where子句加快這:

and attribute_id in ('289', '259', '351') 

順便說一句:request_id和attribute_id真的是字符串還是你爲什麼要在數字上使用引號?

1

通過REQUEST_ID試試這個

select 
    request_id, 
    MIN(case when attribute_id = '289' then attribute_value end) as name, 
    MIN(case when attribute_id = '259' then attribute_value end) as country, 
    MIN(case when attribute_id = '351' then attribute_value end) as priority 
from (
    select a.request_id, a.attribute_id, a.attribute_value 
    from requesttool.request_detail a 
    where a.request_id='4500161635') 
GROUP BY request_id 
相關問題