sql语句查询最后的数据

时间:2014-07-06 17:11:11

标签: sql sql-server date

我开始学习如何编写sql语言,但我遇到了以下问题:现在我在名为'data'的表中有数据

+------+----------------------+
| id  | date                  |
+------+----------------------+
|    1 | 2009-05-10 09:17:25  |
|    2 | 2010-04-09 09:17:25  |
|    3 | 2010-12-12 09:17:25  |
|    4 | 2011-01-11 09:17:25  |
|    5 | 2012-03-19 09:17:25  |
|    7 | 2012-05-20 09:17:25  |
|    8 | 2013-02-21 09:17:25  |
|    9 | 2013-02-02 09:17:25  |
+------+----------------------+

我想写一个sql语句去年从sysdate获得3,所以我想得到的结果是

+------+
| date |
+------+
| 2011 |
| 2012 |
| 2013 |
+------+

假设我们并不确切知道有多少种不同类型和数量的列,那么您能否指导我如何处理这个问题?

提前致谢

4 个答案:

答案 0 :(得分:1)

您可以使用top

SELECT   DISTINCT TOP 3 YEAR([date]) AS [date]
FROM     my_table
ORDER BY YEAR([date]) DESC

答案 1 :(得分:1)

您可以使用以下查询。

WITH years([year])
AS
(
    SELECT DISTINCT YEAR([date]) AS [year]
    FROM my_table
        ORDER BY YEAR([date]) DESC
)
SELECT TOP 3 [year]
FROM years 
ORDER BY [year] ASC;

答案 2 :(得分:0)

您可以尝试此查询:

WITH years([year])
AS
(
SELECT   DISTINCT TOP 3 YEAR([date]) AS [date]
FROM     Table1
ORDER BY YEAR([date]) DESC
)
SELECT TOP 3 [year]
FROM years 
ORDER BY [year] ASC;

SQL FIDDLE DEMO

答案 3 :(得分:0)

尝试以下查询:

SELECT DISTINCT TOP(3) YEAR(date) AS date
FROM YourTable
ORDER BY YEAR(date) DESC