考虑到这个问题
查询STATION中城市最短和最长的两个城市 名称及其各自的长度(即:字符数 在名字里)。如果有不止一个最大的城市, 选择按字母顺序排列的第一个。
Input Format The STATION table is described as follows:
其中LAT_N是北纬,LONG_W是西纬 经度。
Sample Input Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY Sample Output ABC 3 PQRS 4
这是我的解决方法。
SELECT TOP 1 * FROM CITY, LEN(CITY) FROM STATION ORDER BY LEN(CITY), CITY ASC;
SELECT TOP 1 * FROM CITY, LEN(CITY) FROM STATION ORDER BY LEN(CITY) DESC;
根据我的阅读情况W3 schools TOP
SELECT TOP 3 * FROM Customers;
我的解决方案应该起作用。
但是,我收到此错误。
Msg 156, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 6
Incorrect syntax near the keyword 'FROM'.
Msg 156, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 7
Incorrect syntax near the keyword 'FROM'.
答案 0 :(得分:1)
由错误引起的len
函数可能放在select
子句中,而不是from
子句
您可以尝试将ROW_NUMBER
与窗口功能结合使用,以CITY ASC
(根据您的逻辑)创建行号顺序,然后获得rn = 1
行。
select CITY,LEN(CITY) from (
SELECT *,ROW_NUMBER() OVER(PARTITION BY LEN(CITY) ORDER BY CITY ASC) rn
FROM STATION
) t1
where t1.rn =1
答案 1 :(得分:1)
尝试:
SELECT CITY, length FROM
(
select TOP 1 CITY, LEN(CITY) as length
from STATION
order by LEN(CITY)
) [Min]
UNION ALL
SELECT CITY, length FROM
(
select TOP 1 CITY, LEN(CITY) as length
from STATION
order by LEN(CITY) desc
) [Max]
答案 2 :(得分:1)
星号用于“选择所有列”,如果要添加更多列,则列名和星号必须用逗号分隔。由于您要明确指定列,因此请勿使用星号。另外:您经常使用FROM
一词。不得在字段名称前使用,而在表名称前使用
SELECT TOP 1 CITY, LEN(CITY) AS LENGTH FROM STATION ORDER BY LEN(CITY), CITY;
SELECT TOP 1 CITY, LEN(CITY) AS LENGTH FROM STATION ORDER BY LEN(CITY) DESC, CITY;
如果您只想通过一个查询来检索两行,请使用UNION
查询:
SELECT TOP 1 CITY, LEN(CITY) AS LENGTH FROM STATION ORDER BY LEN(CITY), CITY
UNION ALL
SELECT TOP 1 CITY, LEN(CITY) AS LENGTH FROM STATION ORDER BY LEN(CITY) DESC, CITY;