国家和地区的订购查询给出的场景的城市数据

时间:2018-06-06 10:27:16

标签: sql oracle sql-order-by

我的输入数据如下:

**Country          city**
Australia     Sydney
Australia     melbourne
India         Delhi
India         Chennai
India         Bangalore
Afghanistan   Kabul

预期输出为:

Afghanistan
Kabul
Australia
melbourne
syndey
India
Bangalore
Chennai
Delhi

两列中的数据应按字母顺序排列(城市级别和国家级别),结果应为具有上述值的单列。该国家应按字母顺序排列,相应的城市应低于它们,这些城市也应按字母顺序排列。 如果不在单个查询中使用中间表,怎么做呢?

2 个答案:

答案 0 :(得分:2)

您需要UNION ALL个查询才能在每个国家/地区获得一行,并在结果中获得每个城市一行:

select coalesce(city, country) as location
from
(
  select distinct country, null as city from mytable
  union all
  select country, city from mytable
)
order by country, city nulls first;

答案 1 :(得分:1)

这有一个表扫描,也不需要使用UNION来获得不同的结果:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE cities ( Country, city ) AS
SELECT 'Australia',     'Sydney' FROM DUAL UNION ALL
SELECT 'Australia',     'melbourne' FROM DUAL UNION ALL
SELECT 'India',         'Delhi' FROM DUAL UNION ALL
SELECT 'India',         'Chennai' FROM DUAL UNION ALL
SELECT 'India',         'Bangalore' FROM DUAL UNION ALL
SELECT 'Afghanistan',   'Kabul' FROM DUAL;

查询1

SELECT value
FROM   (
  SELECT c.*,
         country AS ctry,
         ROW_NUMBER() OVER ( PARTITION BY Country ORDER BY city ) AS rn
  FROM   cities c
)
UNPIVOT( value FOR key IN ( Country AS 1, City AS 2 ) )
WHERE rn = 1 OR key = 2
ORDER BY ctry, rn, key

<强> Results

|       VALUE |
|-------------|
| Afghanistan |
|       Kabul |
|   Australia |
|      Sydney |
|   melbourne |
|       India |
|   Bangalore |
|     Chennai |
|       Delhi |