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

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

    This is an approach with a CTE. First it finds the longest and shortest, than the matching cities:

    DECLARE @tbl TABLE(CityName VARCHAR(100));
    INSERT INTO @tbl VALUES ('xy'),('Long name'),('very long name'),('middle'),('extremely long name');
    
    WITH MyCTE AS 
    (
        SELECT MAX(LEN(CityName)) AS Longest
              ,MIN(LEN(CityName)) AS Shortest
        FROM @tbl
    )
    SELECT * 
    FROM MyCTE
    --You must think about the chance of more than one city matching the given length
    CROSS APPLY(SELECT TOP 1 CityName FROM @tbl WHERE LEN(CityName)=Longest) AS LongestCity(LongName)
    CROSS APPLY(SELECT TOP 1 CityName FROM @tbl WHERE LEN(CityName)=Shortest) AS ShortestCity(ShortName)
    

    The result

    Longest Shortest    LongName               ShortName
    19       2          extremely long name    xy
    

提交回复
热议问题