您可以使用an analytic function像dense_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
[請張貼文本,而不是屏幕截圖](http://meta.stackoverflow.com/問題/ 303812 /勸阻-截圖-的代碼和有或錯誤)。並展示你迄今爲止所嘗試的以及你有哪些問題;和你需要的實際輸出 - 全部也作爲文本。另外,你如何決定哪個值得到1,哪個得到2等? –
我能夠連接縣和城市列。但是,對它不加限制似乎對我來說是個挑戰。我應該沒有根據第一表中可用排序 – Vinny
親愛的亞歷克斯作爲sugested我創建了一切作爲文本,並來編號 - 列必須按默認排序順序去。 – Vinny