结果未从子查询中选择

时间:2017-09-27 07:19:11

标签: sql-server

我有下表,我执行此查询期望获得201705

SELECT top 1 TIME FROM
(
    SELECT TOP 3 TIME
    FROM TABLE
    WHERE TIME >= 201703
) t
Order by TIME desc

然而,我得到201712 ..

TIME
201605
201606
201607
201608
201609
201610
201611
201612
201701
201702
201703
201704
201705
201706
201707
201708
201709
201710
201711
201712

1 个答案:

答案 0 :(得分:0)

您不需要子查询,但每当您使用TOP(n)时,您还需要使用ORDER BY

SELECT TOP(1) [TIME]
FROM TABLE
WHERE [TIME] >= 201703
ORDER BY [TIME] DESC

“time”是T-SQL中使用的一个词(作为数据类型),因此请使用[]或“”来确保它不会被误解。我不建议将“日期”或“时间”作为列名。

如果它是第三个最新的条目,请尝试此

SELECT TOP (1) [TIME]
FROM (
    SELECT TOP (3) [TIME]
    FROM TABLE
    WHERE TIME >= 201703
    ORDER BY [TIME] DESC
) t
ORDER BY [TIME] ASC