2017-02-15 49 views
-2

我需要將列連接成單行,但我需要將數字作爲序列號添加到每列。請爲SQL開發人員提供代碼,以便我可以在業務對象中實現它。如何連接列以使用Oracle中的數字行SQL Developer

示例源數據

需要
Region Country  City      
------- ----------- ---------- 
Asia Bangladesh Dhaka     
Asia India  Bengaluru     
Asia India  Delhi     
Asia India  Hyderabad     
Asia Pakistan Karachi     
Asia Pakistan Peshawar      
Europe Germany  Berlin     
Europe Germany  Munich     
Europe UK   Leeds     
Europe UK   London     
Europe France  Paris 

輸出:

Region Country        City 
------- ----------------------------------- ------------------------------------------------------------- 
Asia 1. Bangladesh 2.India 3.Pakistan 1. Dhaka 2. Bengaluru, Delhi,Hyderabad 3.Karachi, Peshawar 
Europe 1.Germany 2.UK 3. France   1. Berlin, Munich 2. Leeds, London 3. Paris 
+2

[請張貼文本,而不是屏幕截圖](http://meta.stackoverflow.com/問題/ 303812 /勸阻-截圖-的代碼和有或錯誤)。並展示你迄今爲止所嘗試的以及你有哪些問題;和你需要的實際輸出 - 全部也作爲文本。另外,你如何決定哪個值得到1,哪個得到2等? –

+0

我能夠連接縣和城市列。但是,對它不加限制似乎對我來說是個挑戰。我應該沒有根據第一表中可用排序 – Vinny

+0

親愛的亞歷克斯作爲sugested我創建了一切作爲文本,並來編號 - 列必須按默認排序順序去。 – Vinny

回答

0

您可以使用an analytic functiondense_rank()得到了國家的編號;沒有默認的排序順序(堆表中的數據是一個集合,而不是一個有序集合),所以這個順序按國家名稱 - 如果你有另一個列,你沒有顯示你想排序,然後用它來代替。然後,您可以使用listagg()(從11g開始)進行字符串聚合,以便將每個國家/地區的城市作爲單個字符串排列 - 再次按國家/地區名稱排序,因爲沒有其他明顯的候選字段。

select continent, 
    dense_rank() over (partition by continent order by country) ||'.'|| country as country, 
    dense_rank() over (partition by continent order by country) ||'.'|| 
    listagg(city, ',') within group (order by city) as cities 
from t 
group by continent, country 
order by continent, country; 

CONTIN COUNTRY   CITIES             
------ --------------- -------------------------------------------------------- 
Asia 1.Bangladesh 1.Dhaka             
Asia 2.India   2.Bengalaru,Delhi,Hyderabad        
Asia 3.Pakistan  3.Karachi,Peshawar          
Europe 1.France  1.Paris             
Europe 2.Germany  2.Berlin,Munich           
Europe 3.UK   3.Leeds,London           

如果你真的想在每個洲一行的輸出,你可以做進一步的字符串聚集:

select continent, 
    listagg(country, ' ') within group (order by country_num) as countries, 
    listagg(cities, ' ') within group (order by country_num) as cities 
from (
    select continent, 
    dense_rank() over (partition by continent order by country) as country_num, 
    dense_rank() over (partition by continent order by country) ||'.'|| country as country, 
    dense_rank() over (partition by continent order by country) ||'.'|| 
     listagg(city, ',') within group (order by city) as cities 
    from t 
    group by continent, country 
) 
group by continent 
order by continent; 

CONTIN COUNTRIES       CITIES             
------ ------------------------------------ -------------------------------------------------------- 
Asia 1.Bangladesh 2.India 3.Pakistan  1.Dhaka 2.Bengalaru,Delhi,Hyderabad 3.Karachi,Peshawar 
Europe 1.France 2.Germany 3.UK    1.Paris 2.Berlin,Munich 3.Leeds,London     
相關問題