|
| 1 | + |
| 2 | +https://www.hackerrank.com/challenges/weather-observation-station-5/problem?isFullScreen=true |
| 3 | + |
| 4 | +The text is a SQL query that asks for the two cities in a table named STATION with the shortest and longest names, and their respective lengths. The query also specifies that if there are ties, the city that comes first in alphabetical order should be selected. |
| 5 | + |
| 6 | +-------------- |
| 7 | + |
| 8 | +There are different ways to write this query in SQL, depending on the database system and the syntax it supports. Here are some possible solutions: |
| 9 | +- Using LIMIT and UNION ALL keywords, which are supported by MySQL and PostgreSQL : |
| 10 | + |
| 11 | +(select city, length(city) from station order by length(city) asc, city limit 1) |
| 12 | +union all |
| 13 | +(select city, length(city) from station order by length(city) desc, city limit 1); |
| 14 | + |
| 15 | +- Using TOP and UNION ALL keywords, which are supported by SQL Server and MS Access : |
| 16 | + |
| 17 | +select top 1 city, len(city) from station order by len(city) asc, city |
| 18 | +union all |
| 19 | +select top 1 city, len(city) from station order by len(city) desc, city; |
| 20 | + |
| 21 | +- Using FETCH FIRST and UNION ALL keywords, which are supported by Oracle 12c and IBM DB2 : |
| 22 | + |
| 23 | +(select city, length(city) from station order by length(city) asc, city fetch first 1 row only) |
| 24 | +union all |
| 25 | +(select city, length(city) from station order by length(city) desc, city fetch first 1 row only); |
| 26 | + |
| 27 | +- Using MIN and MAX functions with KEEP and DENSE_RANK keywords, which are supported by Oracle: |
| 28 | + |
| 29 | +select |
| 30 | + min(city) keep (dense_rank first order by length(city) asc) as shortest_city, |
| 31 | + min(city) keep (dense_rank first order by length(city) desc) as longest_city, |
| 32 | + min(length(city)) as min_len, |
| 33 | + max(length(city)) as max_len |
| 34 | +from station; |
| 35 | + |
| 36 | +Summary: These are some of the possible ways to write a SQL query to find the two cities in STATION with the shortest and longest names, and their respective lengths. Is there anything else I can help you with? 😊 |
0 commit comments