在工会双方订购

时间:2016-08-22 04:55:52

标签: sql tsql

我需要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'. 放在整个查询的末尾,它就不会做我想做的事,如果你有另一种方法可以做到这一点,我会很感激建议......

当我运行此查询时,我收到此错误:

forEach

我该怎么办?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

首先为len(city)指定列

喜欢len(city) as lencity

并且不要在两个声明中排序,它没有任何区别......它的最终订单很重要..并且聚合中不需要订购

所以你的陈述可以是..

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