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

后端 未结 29 2009
春和景丽
春和景丽 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:24
    SELECT MAX(LENGTH(transaction_id)) AS Longest ,MIN(LENGTH(transaction_id)) AS Shortest FROM cards
    
    0 讨论(0)
  • 2021-01-31 00:25

    In Oracle, we can do like this

    select city, length(city)
    from (select city from STATION order by length(city) DESC, city ASC)
    where rownum = 1 
    union
    select city, length(city)  
    from (select city from STATION order by length(city), city ASC)
    where rownum = 1;
    

    The idea is to get the longest and shortest city then union them into one result.

    0 讨论(0)
  • 2021-01-31 00:26

    Maybe a simpler option since I imagine you are looking for help with a solution to a Hacker Rank question? The addition of limits made it simpler for me to debug where the issue was with the returned error.

    SELECT city, length(city) FROM station order by length(city) desc limit 1;
    
    SELECT city, length(city) FROM station order by length(city) asc, city asc limit 1
    
    0 讨论(0)
  • 2021-01-31 00:30

    I think this should work:

        SELECT MAX(CITY) , LENGTH(MAX(CITY)) FROM STATION;
        SELECT MIN(CITY) , LENGTH(MIN(CITY)) FROM STATION;
    
    0 讨论(0)
  • 2021-01-31 00:31

    This is another way of doing it in MySQL. May not be the best, but still be an option that is logically correct.

    select
       city,
       length(city) 
    from
       station 
    where
       length(city) in 
       (
          select
             max(length(city)) 
          from
             station 
          union
          select
             min(length(city)) 
          from
             station
       )
    order by
       length(city) desc,
       city asc limit 2;
    
    0 讨论(0)
  • 2021-01-31 00:32

    This Query will work well in your condition these 2 query are exactly same. In the first query we just ordering the recording in descending order to take the city name with the highest length and in the second part we are just taking records in the ascesding order to take city with the minimum lenght all the rest query is same. Kidnly have a look.

    Detail:

    1. Select statement to take out records
    2. Use group by clause because I am using Len() aggregating function.
    3. Ordering all the retrieved records in the descending and ascending order to get the top 1 and take max and min length city.

      select  Top 1  City,max(len(City)) as Length  
      from STATION 
      group by City 
      ORDER BY Length desc 
      
      select  Top 1  City,max(len(City)) as Length  
      from STATION 
      group by City 
      ORDER BY Length ASC
      
    0 讨论(0)
提交回复
热议问题