简体   繁体   中英

How to get shortest and longest string from table?

Suppose, I have a table Station in SQL Server:

|  ID  | Name |
+------+------+
|  1   | a    |
|  2   | b    |
|  3   | cc   |
|  4   | ddd  |
|  5   | eee  |

I want to retrieve shortest and Longest name along with length (in case of a tie, it will show alphabetically top 1) so, the output will be

|  a  |   1  |
+-----+------+
| ddd |   3  |

I tried this:

Select  
    Name, len(name) 
from 
    Station 
where 
    len(name) = (Select min(len(name)) from Station) 
union

Select  
    Name, len(name) 
from 
    Station 
where 
    len(name) = (Select max(len(name)) from Station) 

But, I have to take the alphabetically first only which I am not able to do

SELECT *
FROM
    (SELECT TOP(1) *, LEN(name) as ln
    FROM Student
    ORDER BY ln, name
    UNION
    SELECT TOP(1) *, LEN(name) as ln
    FROM Student
    ORDER BY ln DESC, name) as tblMain
select  *
from    (
        select  name
        ,       row_number() over (order by len(name), name) rn1
        ,       row_number() over (order by len(name) desc, name) rn2
        from    student
        ) sub
where   rn1 = 1  -- Shortest name
        or rn2 = 1  -- Longest name

Your method would work with a slight tweak:

Select  min(Name) as name, len(name)
from Station 
where len(name) = (Select min(len(name)) from Station) 
group by len(name)
union all
Select min(Name) as name, len(name)
from Station 
where len(name) = (Select max(len(name)) from Station) 
group by len(name);

or:

Select min(Name) as name, min(len(name))
from Station 
where len(name) = (Select min(len(name)) from Station) 
union all
Select min(Name) as name, min(len(name))
from Station 
where len(name) = (Select max(len(name)) from Station) ;

That is, by aggregation you get one row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM