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

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

    I did this in SQL Server using CTE and dense_rank function. How the ranking works?

    First partition (form groups) over the lengths, i.e same lengths make a group (partition). Then order all the names alphabetically within each partition. Then assign ranks (dRank column) within each partition. So rank 1s in each group will be assigned to names which alphabetically appear first in their respective partition. All this happens in the common table expression (cte block)

    "with cte as
    (
    select *, LEN(city) as length, DENSE_RANK() over (partition by len(city) order by city) as dRank from Station
    )"
    
    select city,length from cte where dRank = 1 and length = (select MIN(length) from cte)
    UNION
    select city,length from cte where dRank = 1 and length = (select max(length) from cte)"
    

提交回复
热议问题