我编写了一个查询,以返回 MS SQL SERVER 数据库中具有最短和最长长度字符串的城市。
Select city, len(city) as l
From Station Where len(city) in
((select max(len(city)) from station)
Union
(select min(len(city)) from station))
Order by l,city;
我的困难是我得到了重复项,因为我有几个城市的长度最长和最短。另外,当我在两个子查询中尝试
ORDER BY CITY
时,它都会失败。
有什么建议吗?
我可能会这样做:
select top (1) with ties city
from station
order by len(city) asc
union
select top (1) with ties city
from station
order by len(city) desc;
或者:
select distinct city
from station
where len(city) = (select max(len(city)) from station) or
len(city) = (select min(len(city)) from station);
另一种方式:
select * from (
select top 1 city, LEN(city) cityLength from station order by cityLength ASC,city ASC) Minimum
UNION
select * from (
select top 1 city, LEN(city) cityLength from station order by cityLength desc, city ASC) Maximum
选择城市,长度(城市)从车站所在城市(从车站选择城市,长度(城市)在(选择最大(长度(城市))从车站))或城市(从车站选择最小(城市),其中长度(City) in (Select min(length(City)) from Station)) 按城市 asc 排序;
SELECT CITY, LENGTH(CITY) lengthOfCity FROM STATION
ORDER BY lengthOfCity asc, CITY asc
LIMIT 1;
SELECT CITY, LENGTH(CITY) lengthOfCity FROM STATION
ORDER BY lengthOfCity desc, CITY asc
LIMIT 1;.
您需要将 ORDER BY 与 2 个变量一起使用来证明条件的合理性。
Declare @min as int
Declare @max as int
select @min =min(len(city)) , @max =max(len(city)) From Station
Select city , lengthcity From (
Select city,len(city)lengthcity, row_number() over(partition by len(city) order by city)rn from Station where len(city) in (@min , @max)
) a
where rn=1
这是解决这个问题的简单方法
(Select Distinct CITY, Length(CITY)
FROM STATION
WHERE LENGTH(CITY) IN
(Select MIN(Length(CITY)) from STATION)
Order BY CITY ASC
LIMIT 1)
UNION
(Select Distinct CITY, Length(CITY)
FROM STATION
WHERE LENGTH(CITY) IN
(Select MAX(Length(CITY)) from STATION)
Order BY CITY ASC
LIMIT 1)
我就是这样解决的
Declare @ShortLength INT
SET @ShortLength = (SELECT MIN(LEN(CITY)) FROM STATION)
Declare @LongLength INT
SET @LongLength = (SELECT MAX(LEN(CITY)) FROM STATION)
SELECT TOP (1) CITY AS City, LEN(CITY) AS ShortLength FROM STATION WHERE LEN(CITY) =
@ShortLength ORDER BY CITY ASC
SELECT TOP (1) CITY AS City, LEN(CITY) AS LongLength FROM STATION WHERE LEN(CITY) =
@LongLength ORDER BY CITY ASC;
对我来说效果很好
以 cte 为(选择前 1 个城市,len(城市)作为长度 从车站 其中 len(city)=(从车站选择 min(len(city))) 按城市升序排列) ,cte2 作为 ( 选择 city ,len(city) 作为长度 从车站 其中 len(city)=(从车站选择 max(len(city))))
选择城市,距离 cte 的长度 联盟 选择城市,从cte2开始的长度;