查找字符串的最大长度+ Oracle SQL中的字符串

时间:2016-04-07 09:53:48

标签: sql oracle

这是针对数据库(https://www.hackerrank.com/challenges/weather-observation-station-5)的HackerRank Weather Observation 5问题。我该如何解决这个问题?

  

使用最短和最长的CITY查询STATION中的两个城市   名称,以及它们各自的长度(即:字符数   在名字里)。如果有多个最小或最大的城市,   选择按字母顺序排序的第一个。

这是我到目前为止所拥有的

SELECT CITY, MAX LENGTH(CITY) FROM STATION;

但它显然不起作用。

6 个答案:

答案 0 :(得分:1)

这是一个带窗函数的解决方案:

select city, length(city)
from
(
  select 
    city, 
    row_number() over (order by length(city), city) as shortest_is_one,
    row_number() over (order by length(city) desc, city) as longest_is_one
  from station
)
where shortest_is_one = 1 or longest_is_one = 1;

替代方案是使用UNION的{​​{1}}查询:

FETCH FIRST 1 ROW ONLY

这又是另一个查询,再次使用( select city, length(city) from station order by length(city), city fetch first 1 row only ) union ( select city, length(city) from station order by length(city) desc, city fetch first 1 row only );

UNION

答案 1 :(得分:1)

在单表扫描中:

SELECT MIN( city ) KEEP ( DENSE_RANK FIRST ORDER BY LENGTH( city ) ) AS shortest_city,
       MIN( city ) KEEP ( DENSE_RANK LAST  ORDER BY LENGTH( city ) ) AS longest_city,
       LENGTH( MIN( city ) KEEP ( DENSE_RANK FIRST ORDER BY LENGTH( city ) ) )
         AS shortest_length,
       LENGTH( MIN( city ) KEEP ( DENSE_RANK LAST  ORDER BY LENGTH( city ) ) )
         AS longest_length
FROM   station;

<强>解释

使用... KEEP ( DENSE_RANK [FIRST|LAST] ORDER BY ...)时,您可以从右向左阅读以评估其效果。

所以:

MIN( city ) KEEP ( DENSE_RANK FIRST ORDER BY LENGTH( city ) )

威尔:

  1. ORDER BY子句按城市长度排序结果;然后
  2. KEEP ( DENSE_RANK FIRST子句仅保留在顺序中排名第一的结果(并且如果有多个结果在顺序中排在第一位,那么它将保留所有首先联合的结果);最后,
  3. MIN( city )将从保留的结果(即只有长度最短的结果)中返回city的最小值(即字母顺序的名字)。

答案 2 :(得分:1)

这是我的解决方案。我不确定性能,但它对我来说效果很好,而且不难理解。基本上我们只是选择城市和城市的长度并将其存储在var'len_city'中,诀窍是我们将它们列为升序,但将列表限制为一个。然后我们用相同的查询结合该答案,这次,通过降序排序,但也限于一个。这样我们得到第一个最短和最后一个。我对更简单的实现持开放态度,但这不是火箭科学,其他可能更难理解但更有效。我对此很新,但不是编程,所以,希望这有帮助!

(SELECT city, CHAR_LENGTH(city) AS len_city FROM station ORDER BY len_city ASC LIMIT 1)
UNION ALL
(SELECT city, CHAR_LENGTH(city) AS len_city FROM station ORDER BY len_city DESC LIMIT 1)

答案 3 :(得分:1)

(select min(city) count(min(city)) from station order by city )
union all
(select max(city) count(max(city)) from station order by city desc);

答案 4 :(得分:0)

(SELECT city, CHAR_LENGTH(city) as val1 FROM station order by  CHAR_LENGTH(city) ASC limit 0,1) 
UNION ALL 
(SELECT city, CHAR_LENGTH(city) as val2 FROM station order by CHAR_LENGTH(city) DESC limit 0,1)

答案 5 :(得分:0)

select CITY
  , length(CITY)
from station
order by length(CITY), city
limit 1; 

select CITY
  , length(CITY)
from station
order by length(CITY) desc, city
limit 1;