是否可以按表中的字符选择最短和最长的字符串?
我有一个类型为CITY
的{{1}}列,我希望按字母顺序选择最短和最长的城市名称。
我这样做了
VARCHAR(20)
按字母顺序排序时,让CITY名称列为ABC,DEF,PQRS和WXY,各自的长度分别为3,3,4和3.最长的城市显然是PQRS,但有最短的选项 - 命名的城市;我必须选择ABC,因为它首先按字母顺序排列。
我的查询结果是所有三个城市的长度都为3。
SELECT CITY,LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY) IN (
SELECT MAX(LENGTH(CITY))
FROM STATION
UNION
SELECT MIN(LENGTH(CITY))
FROM STATION
)
ORDER BY CITY ASC;
SELECT的结果必须是
ABC 3
DEF 3
PQRS 4
WXY 3
答案 0 :(得分:0)
您可以使用UNION运算符
(SELECT CITY, MAX(LENGTH(CITY)) FROM STATION)
UNION
(SELECT CITY, MIN(LENGTH(CITY)) FROM STATION)
ORDER BY CITY ASC LIMIT 1;
答案 1 :(得分:0)
尝试这些查询。
最长城市名称::
select CITY from STATION where char_length(CITY) = (select max(char_length(CITY)) from STATION)
最短城市名称::
select CITY from STATION where char_length(CITY) = (select min(char_length(CITY)) from STATION)
答案 2 :(得分:0)
如果我理解正确的话,我认为你需要union
子查询:
select s.*
from station s
where length(city) in (select max(length(city))
from station
union
select min(length(city))
from station)
order by length(city);
答案 3 :(得分:0)
无论如何我得到了答案
SELECT CITY,LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY) IN (
SELECT MAX(LENGTH(CITY))
FROM STATION
UNION
SELECT MIN(LENGTH(CITY))
FROM STATION
)
ORDER BY LENGTH(CITY) DESC,CITY ASC LIMIT 2;
答案 4 :(得分:0)
我知道您已经选择了答案,但这是一个简短的答案,可能会有所帮助。 这是使用Microsoft MySQL Server,但也可以使用调用LIMIT而不是TOP轻松转换为任何其他类型。
最长
SELECT TOP 1 CITY, LEN(CITY)
FROM STATION
ORDER BY LEN(CITY) ASC, CITY ASC;
最短长度
SELECT TOP 1 CITY, LEN(CITY)
FROM STATION
ORDER BY LEN(CITY) DESC, CITY ASC;
答案 5 :(得分:0)
我发现这很简单:
`选择城市,从中选择城市长度(从按车站长度排序的城市中选择城市(城市ASC,城市ASC) WROWE ROWNUM = 1;
选择城市,从中选择城市长度(从按车站长度排序的城市中选择城市(城市)DESC,城市ASC) WROWE ROWNUM = 1;`
答案 6 :(得分:0)
我已经尝试过了,找到了MySQL数据库查询的解决方案,
(SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY LENGTH(CITY) ASC, CITY ASC LIMIT 1)
UNION
(SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY LENGTH(CITY) DESC, CITY ASC LIMIT 1)
我认为使用LIMIT比行号更好。
答案 7 :(得分:0)
请在下面的查询中找到此内容:
SELECT top 2 CITY,LEN(CITY)
FROM STATION
WHERE LEN(CITY) IN (
SELECT MAX(LEN(CITY))
FROM STATION
UNION
SELECT MIN(LEN(CITY))
FROM STATION
)
ORDER BY LEN(CITY) DESC,CITY ASC ;
答案 8 :(得分:0)
更清洁的方式:
SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) ASC, CITY ASC LIMIT 1;
SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC, CITY ASC LIMIT 1;
答案 9 :(得分:0)
SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY),CITY LIMIT 1;
SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC, CITY LIMIT 1;
上面的代码应该很容易理解并且易于理解。第一个查询显示最短的城市名称及其长度。第二个输出最长。
答案 10 :(得分:0)
@DecimalMax