【问题标题】:Query to find the city name with longest and shortest length查询长度最长和最短的城市名称
【发布时间】:2018-05-07 20:35:04
【问题描述】:

我编写了一个查询来返回 MS SQL SERVER 数据库中长度最短和最长的城市。

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;

我的困难是我得到了重复,因为我有几个城市的长度最长和最短。此外,当我在两个子查询中尝试 ORDER BY CITY 时,它都会失败。

有什么建议吗?

【问题讨论】:

    标签: sql sql-server-2008 subquery union


    【解决方案1】:

    我可能会这样做:

    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);
    

    【讨论】:

    • ties 应该做什么?第一个查询出现运行时错误。也不确定 Union 和 UNION ALL 之间有什么区别,但我可以用谷歌搜索!第二个查询给了我和我一样的结果(仍然有重复)
    • 使用'选择不同的城市...'
    【解决方案2】:

    另一种方式:

    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
    

    【讨论】:

    • 效果很好。你知道我在哪里可以找到关于以这种方式使用的最小值和最大值的信息吗?我只知道查询的 Select 部分中使用的 min(attribute) 和 max(attribute) 聚合。
    • 我不确定该去哪里看,但我基本上只是在选择 Len(city) 并按“asc”和“desc”排序时获得了 Top 1。这将获得每个选择的最小值和最大值。
    【解决方案3】:

    Select City, length(City) from Station where City in (Select City from Station where length(City) in (Select max(length(City)) from Station)) OR City in (Select min(City) from Station where length(City) in (Select min(length(City)) from Station)) order by City asc;

    【讨论】:

    • 这并不能真正回答问题。如果您可以添加解释,那就太好了。为什么这个 sn-p 是解决方案?
    【解决方案4】:

    哇!!

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

    Declare @ShortLength INT 
    SET @ShortLength = (SELECT MIN(LEN(CITY)) FROM STATION)
    Declare @LongLength INT 
    SET @LongLength = (SELECT MAX(LEN(CITY)) FROM STATION)
    SELECT TOP (1) CITY AS City, LEN(CITY) AS ShortLength FROM STATION WHERE LEN(CITY) = 
    @ShortLength ORDER BY CITY ASC
    SELECT TOP (1) CITY AS City, LEN(CITY) AS LongLength FROM STATION WHERE LEN(CITY) = 
    @LongLength ORDER BY CITY ASC;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2021-10-28
      相关资源
      最近更新 更多