Basic Select
Weather Observation Station 5
PROBLEM
Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.
The STATION table is described as follows:
where LAT_N is the northern latitude and LONG_W is the western longitude.
Sample Input
For example, CITY has four entries: DEF, ABC, PQRS and WXY.
Sample Output
Explanation
When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS, and WXY, with lengths 3,3,4
and 3. The longest name is PQRS, but there are 3 options for shortest named city. Choose ABC, because it comes first alphabetically.
Note
You can write two separate queries to get the desired output. It need not be a single query.
ANSWER
MS SQL
SELECT TOP 1 CITY,LEN(CITY) FROM STATION
ORDER BY LEN(CITY) ASC, CITY ;
SELECT TOP 1 CITY,LEN(CITY) FROM STATION
ORDER BY LEN(CITY) DESC, CITY ;
MySQL
SELECT CITY ,LENGTH(CITY) FROM STATION
ORDER BY LENGTH(CITY) ASC , CITY limit 1;
SELECT CITY ,LENGTH(CITY) FROM STATION
ORDER BY LENGTH(CITY) DESC , CITY limit 1;
这个题目需要注意SQL Server和MySQL的语法区别。
文本字段中值的长度应该由LEN()或LENGTH() (MySQL) 函数来返回。
SQL Server使用 SELECT TOP子句来返回指定条数的数据;MySQL则使用LIMIT语句。
关于ORDER BY:
多个列排序时,排序具有优先级,order by a,b中,a的优先级大于b,只有到a的值相同时才会排b的序。
且DESC关键字只应用到直接位于其前面的列名,所以在上述答案中,只对长度指定,对CITY列不指定,CITY列仍然按照标准升序排序。
Weather Observation Station 12
PROBLEM
Query the list of CITY names from STATION that do not start with vowels and do not end with vowels. Your result cannot contain duplicates.
STATION表同上。
ANSWER
SQL Server
SELECT DISTINCT city FROM STATION
WHERE city LIKE '[^aeiou]%' AND city LIKE '%[^aeiou]';
MySQL
SELECT distinct CITY FROM STATION
WHERE CITY REGEXP '^[^aeiou].*[^aeiou]$';
MySQL中,“[]”属于正则模式,不能使用LIKE+方括号通配符[]。
可以使用正则表达式来检索符合某个模式的文本内容。
MySQL 中使用 REGEXP 关键字指定正则表达式的字符匹配模式,下表列出了 REGEXP 操作符中常用的匹配列表。