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

后端 未结 29 2308
春和景丽
春和景丽 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: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
      

提交回复
热议问题