SQL query for finding the longest name and shortest name in a table

后端 未结 29 2011
春和景丽
春和景丽 2021-01-31 00:11

I have a table with one of the columns is of type varchar(city). and want to find the longest and shortest of values stored in that column.

select a.city, a.city         


        
相关标签:
29条回答
  • 2021-01-31 00:34

    Ascending:

    SELECT city, CHAR_LENGTH(city) FROM station ORDER BY CHAR_LENGTH(city), city LIMIT 1;

    Descending:

    SELECT city, CHAR_LENGTH(city) FROM station ORDER BY CHAR_LENGTH(city) DESC, city LIMIT 1;
    0 讨论(0)
  • 2021-01-31 00:34

    In Oracle 12c, this could be done using FETCH..FIRST

    Shortest

    select * FROM station ORDER BY LENGTH(city) DESC FETCH FIRST 1 ROWS ONLY;
    

    Longest

    select * FROM station ORDER BY LENGTH(city) ASC FETCH FIRST 1 ROWS ONLY;
    
    0 讨论(0)
  • 2021-01-31 00:34

    Shortest:

    select city, char_length(city) city_length from station order by city_length, city limit 1;
    

    Longest:

    select city, char_length(city) city_length from station order by city_length desc, city limit 1;
    
    0 讨论(0)
  • 2021-01-31 00:35

    Initially finding the shortest length of the city and taking an union with the longest length of the city. This minimizes the complexity of the query.

    (select city, char_length(city) as len_city
    from station
    order by len_city limit 1)
    union ( select city, char_length(city) as len_city
        from station
        order by len_city desc limit 1) 
    order by len_city
    
    0 讨论(0)
  • 2021-01-31 00:35
    with cte (rank, city , CityLength) 
    As 
    (select  dense_rank() over (partition by len(city) order by city asc) as Rank, city, len(city) 
        from station 
    where len(city) in 
        ((select max(len(city)) from station) 
        union (select min(len(city)) from station)))
    select city,citylength from cte where rank = 1;
    
    0 讨论(0)
  • 2021-01-31 00:36

    Following query seems simple enough:

    select 
        city, leng 
    from
        (select top 1 
             city, len(city) leng 
         from 
             station 
         where 
             len(city) = (select min(len(city)) from station) 
         order by 
             city
    
         Union all
    
         select top 1 
             city, len(city) leng 
         from 
             station 
         where 
             len(city) = (select max(len(city)) from station)  
         order by 
             city) result;
    

    The 1st query inside returns the city with the minimum length, while the 2nd query returns the city with the maximum length.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题