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

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

    In Oracle (and any other language that supports analytic functions), using the ROW_NUMBER analytic function you can assign the rows a unique number according to ASCending (or DESCending) length of the city. Since there may be multiple rows with the same length then a secondary order can be applied to get the first city of that length alphabetically. Then all you need is an outer query to filter the results to only the shortest (or longest) name:

    SELECT city
    FROM   (
      SELECT CITY,
             ROW_NUMBER() OVER ( ORDER BY LENGTH( CITY ) ASC,  CITY ) shortest_rn,
             ROW_NUMBER() OVER ( ORDER BY LENGTH( CITY ) DESC, CITY ) longest_rn
      FROM   station
    )
    WHERE shortest_rn = 1
    OR    longest_rn  = 1;
    

    If you want to return all the cities with the shortest (or longest) name then use DENSE_RANK instead of ROW_NUMBER:

    SELECT city
    FROM   (
      SELECT CITY,
             DENSE_RANK() OVER ( ORDER BY LENGTH( CITY ) ASC  ) shortest_rn,
             DENSE_RANK() OVER ( ORDER BY LENGTH( CITY ) DESC ) longest_rn
      FROM   station
    )
    WHERE shortest_rn = 1
    OR    longest_rn  = 1
    ORDER BY shortest_rn, city; -- Shortest first and order tied lengths alphabetically
    

提交回复
热议问题