我有一个表,其中一列是varchar(city)类型.并希望找到该列中存储的最长和最短值.
select a.city, a.city_length from (select city, char_length(city) city_length
from station order by city, city_length) a
where a.city_length = (select min(a.city_length) from a) or
a.city_length = (select max(a.city_length) from a)
group by a.city_length;
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?谢谢
一个解决方案
select * from (select city, char_length(city) city_length from station order by city, city_length) a group by a.city_length order by a.city_length limit 1;
select * from (select city, char_length(city) city_length from station order by city, city_length) a group by a.city_length order by a.city_length desc limit 1;
Run Code Online (Sandbox Code Playgroud)
Ban*_*yan 20
我认为我们不需要使用Min和Max函数,也不需要Group by.
我们可以使用以下代码实现此目的:
select top 1 City, LEN(City) City_Length from STATION order by City_Length ASC,City ASC
select top 1 CITY, LEN(city) City_Length from station order by City_Length desc, City ASC
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,它将在2表中显示输出,如果我们想在单个表中组合,那么我们可以使用Union或Union ALL.下面是相同的SQL查询
select * from (
select top 1 City, LEN(City) City_Length from STATION order by City_Length ASC,City ASC) TblMin
UNION
select * from (
select top 1 CITY, LEN(city) City_Length from STATION order by City_Length desc, City ASC) TblMax
Run Code Online (Sandbox Code Playgroud)
这里我将select语句嵌套在子查询中,因为当我们使用order by子句时,我们不能直接使用Union或Union ALL,这就是我在子查询中写入它的原因.
小智 9
最短:
select TOP 1 CITY,LEN(CITY) LengthOfCity FROM STATION ORDER BY LengthOfCity ASC, CITY ASC;
Run Code Online (Sandbox Code Playgroud)
最长:
select TOP 1 CITY,LEN(CITY) LengthOfCity FROM STATION ORDER BY LengthOfCity DESC, CITY ASC;
Run Code Online (Sandbox Code Playgroud)
这适用于HackerRank挑战问题(MS SQL Server).
也许是一个更简单的选择,因为我想您正在寻找有关黑客排名问题的解决方案?限制的增加使我可以更轻松地调试返回错误的问题所在。
SELECT city, length(city) FROM station order by length(city) desc limit 1;
SELECT city, length(city) FROM station order by length(city) asc, city asc limit 1
Run Code Online (Sandbox Code Playgroud)
小智 5
在MySQL中
(select city, LENGTH(city) cityLength from station order by cityLength desc,city asc LIMIT 1)
union all
(select city, LENGTH(city) cityLength from station order by cityLength asc,city asc LIMIT 1)
Run Code Online (Sandbox Code Playgroud)
您的查询只需要进行一些调整。根本问题是您不能a像您所做的那样在子查询中使用:
select a.city, a.city_length
from (select city, char_length(city) city_length
from station
) a
where a.city_length = (select min(char_length(city)) from station) or
a.city_length = (select max(char_length(city)) from station);
Run Code Online (Sandbox Code Playgroud)
也就是说,编写查询的更简单方法是:
select s.*
from station s cross join
(select min(char_length(city)) as mincl, max(char_length(city)) as maxcl
from station
) ss
where char_length(s.city) in (mincl, maxcl);
Run Code Online (Sandbox Code Playgroud)