2016-08-22 61 views
0

两侧,我需要通过city订购union查询的两面:订购工会

select * from(select top(1)city, len(city) from Station  
where len(city) = (select min(len(d.city)) from Station d) order by city) as a 
union all select * from (select top(1) city, LEN(city) from Station 
where len(city) = (select max(len(f.city)) from station f) order by city) as b 

我需要订购两侧,因为如果我有相同长度的两个城市,然后我需要得到第一个按字母顺序,如果我把order by在整个查询结束它不会做我想要的,如果你有另一种方式做到这一点,我将不胜感激的建议..

当我运行这个查询我收到此错误:

Msg 8155, Level 16, State 2, Line 3 
No column name was specified for column 2 of 'a'. 
Msg 8155, Level 16, State 2, Line 4 
No column name was specified for column 2 of 'b'. 

我该怎么办?

回答

1
select * from (select top(1) city, len(city) as 'length' 
       from Station  
       order by len(city) asc, city) as a 
union all 
select * from (select top(1) city, len(city) as 'length' 
       from Station  
       order by len(city) desc, city) as b 
0

固定

select * from(select top(1)city, len(city) as 'length' from Station  
where len(city) = (select min(len(d.city)) from Station d) order by city) as a 
union all select * from (select top(1) city, LEN(city) as 'length' from Station 
where len(city) = (select max(len(f.city)) from station f) order by city) as b 
+0

我意识到,我应该把名字列LEN(市),这是whay错误正在发生:) – AlexGH

0

先为LEN(市)

像指定列len(city) as lencity

,并且不要在这两个语句顺序,不作任何difference..Its最后的订单由重要的..和秩序是不需要在总和

所以你的发言可以..

select * from(select top(1)city, len(city) as lencity 
from Station  
where len(city) = (select min(len(d.city)) from Station d)) as a 
union all 
select * from (select top(1) city, LEN(city) as lencity from Station 
where len(city) = (select max(len(f.city)) from station f) ) as b 
order by lencity 
+0

有了,我把我得到的查询:ABC 3和埃德蒙顿8,是我需要得到什么,和你一起得到def 3和Edmonton 8你看到了区别吗?当我有两个相同长度的城市时,我需要根据字母顺序作出决定。谢谢 – AlexGH

+0

请更新问题或提出新问题 – TheGameiswar