2017-02-15 66 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     
相关问题