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

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

    select city,length(city) from (select city,length(city),rank() over(partition by length(city) order by length(city),city asc) as rnk from station)a where a.rnk=1;

    0 讨论(0)
  • 2021-01-31 00:37
    select top(1) city, max(len(city)) [Length] from station group by city order by [Length]
    select top(1) city, max(len(city)) [Length] from station group by city order by [Length] DESC
    

    Tested in SQL Server 2016

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

    In Oracle:

    select * from (select city, min(length(city)) minl from station group by city order by minl, city) where rownum = 1;
    select * from (select city, max(length(city)) maxl from station group by city order by maxl desc, city) where rownum = 1;
    0 讨论(0)
  • 2021-01-31 00:38

    In Oracle it would be,

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

    Shortest:

    select TOP 1 CITY,LEN(CITY) LengthOfCity FROM STATION ORDER BY LengthOfCity ASC, CITY ASC;
    

    Longest:

    select TOP 1 CITY,LEN(CITY) LengthOfCity FROM STATION ORDER BY LengthOfCity DESC, CITY ASC;
    

    This works for HackerRank challenge problem (MS SQL Server).

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