在同一SQL语句中使用ORDER BY和UNION ALL

时间:2018-12-14 23:21:27

标签: sql sql-server

这为什么不能给出预期的结果?

SELECT top 1 CITY, LEN(CITY) FROM STATION ORDER BY LEN (city) desc
union all 
SELECT top 1 CITY, LEN(CITY) FROM STATION ORDER BY LEN (city) asc;

1 个答案:

答案 0 :(得分:1)

您需要将每个有序查询表示为子查询,因为union无法跟随order by,因此:

select a.* from (select top 1 city, len(city) from station order by len(city) desc) a
union all 
select b.* from (select top 1 city, len(city) from station order by len(city)) b