SQL Server顶部函数返回最小长度的字符串

时间:2018-08-15 23:18:25

标签: sql sql-server

考虑到这个问题

  

查询STATION中城市最短和最长的两个城市   名称及其各自的长度(即:字符数   在名字里)。如果有不止一个最大的城市,   选择按字母顺序排列的第一个。

Input Format

The STATION table is described as follows:

SQL Table schema

  

其中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'. 

3 个答案:

答案 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 

sqlfiddle

答案 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;