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

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

    I used the WITH clause for Oracle to save the shortest /longest names in a temporary variable rather than querying inside the main "from" clause. SQL WITH clause example

    WITH shortnames AS
    (SELECT city, length(city) 
     FROM station 
     ORDER BY length(city) asc, city),
    
     longnames AS
     (SELECT city, length(city) 
      FROM station
      ORDER BY length(city) desc, city)
    
    SELECT * FROM shortnames WHERE ROWNUM=1
    UNION ALL
    SELECT * FROM longnames WHERE ROWNUM=1;
    

提交回复
热议问题