查询以查找长度最长和最短的城市名称

时间:2018-05-07 20:35:04

标签: sql sql-server-2008 subquery union

我编写了一个查询,以便在MS SQL SERVER数据库中返回具有最短和最长字符串的城市。

ArrayList<Long> instead of long[]

我的困难在于我得到了重复,因为我有一些城市的长度最长,最短。此外,当我在两个子查询中尝试Select city, len(city) as l From Station Where len(city) in ((select max(len(city)) from station) Union (select min(len(city)) from station)) Order by l,city; 时,它都会失败。

有什么建议吗?

4 个答案:

答案 0 :(得分:3)

我可能会这样做:

select top (1) with ties city
from station
order by len(city) asc
union 
select top (1) with ties city
from station
order by len(city) desc;

或者:

select distinct city
from station
where len(city) = (select max(len(city)) from station) or
      len(city) = (select min(len(city)) from station);

答案 1 :(得分:0)

另一种方式:

select * from (
         select top 1 city, LEN(city) cityLength from station order by cityLength ASC,city ASC) Minimum
       UNION
       select * from (
       select top 1 city, LEN(city) cityLength from station order by cityLength desc, city ASC) Maximum

答案 2 :(得分:0)

从城市中选择城市,从城市中选择城市的长度(城市)(从城市中选择城市,从(从城市中选择城市的长度(城市),从城市中选择长度(城市)),或从城市中(从城市中选择最小值(城市),选择城市中的城市长度)在(按城市的升序选择(从车站选择min(length(City))))中的length(City)顺序;

答案 3 :(得分:0)

哇!

我今天遇到了这个问题,这就是我的解决方法

tag_depth = 0
for c in mystring:
    if c == '<':
        tag_depth += 1
    elif c == '>':
        tag_depth -= 1
    elif tag_depth == 0:
        print(f"{c}", end=0)