我正在处理一个sql查询,在这里我必须找到过去的10年。假设这是2015年,那么查询应该返回20152014,2013年.诸若此类。为此,我使用了以下查询-
select top 10 DATEPART(Year,getdate()) order by DATEPART(Year,getdate()) desc
但是,上面的查询只返回单个查询,即当前年份。请帮帮我这里的人。
发布于 2015-07-14 10:55:31
试试这个:
with yearlist as
(
select (DATEPART(Year,getdate())-10) as year
union all
select yl.year + 1 as year
from yearlist yl
where yl.year + 1 <= YEAR(GetDate())
)
select year from yearlist order by year desc;
发布于 2015-07-14 11:02:40
您可以这样做:
DECLARE @YearsToPass INT
SET @YearsToPass = 10
;WITH cte AS
(
SELECT DATEPART(YY, GETDATE())- @YearsToPass + 1 as Years
UNION ALL
SELECT Years + 1 as Years
FROM cte
WHERE Years + 1 <= YEAR(GETDATE())
)
SELECT Years
FROM cte
ORDER BY Years DESC
简单地将@YearsToPass
设置为您希望返回的年数。
发布于 2016-03-08 10:42:13
非CTE方法.
SELECT DATEPART(Year,DateAdd(Year,-I,getdate()))
FROM (
SELECT 0 AS I UNION
SELECT 1 AS I UNION
SELECT 2 AS I UNION
SELECT 3 AS I UNION
SELECT 4 AS I UNION
SELECT 5 AS I UNION
SELECT 6 AS I UNION
SELECT 7 AS I UNION
SELECT 8 AS I UNION
SELECT 9 AS I UNION
SELECT 10 AS I
) AS T
对此的统计
Server解析和编译时间: CPU时间=0 ms,运行时间=0 ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。Server解析和编译时间: CPU时间=0 ms,运行时间=4ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。 (11行受影响) (1行受影响) Server执行时间: CPU时间=0 ms,运行时间=1ms。Server解析和编译时间: CPU时间=0 ms,运行时间=0 ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。
CTE的VS统计量
Server解析和编译时间: CPU时间=0 ms,运行时间=0 ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。Server解析和编译时间: CPU时间=0 ms,运行时间=3 ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。 (受影响的11行)表“工作表”。扫描计数2,逻辑读取67,物理读取0,预读读取0,lob逻辑读取0,lob物理读取0,lob预读读取0. (1行受影响) Server执行时间: CPU时间=0 ms,运行时间=3 ms。Server解析和编译时间: CPU时间=0 ms,运行时间=0 ms。 Server执行时间: CPU时间=0 ms,运行时间=0 ms。
https://stackoverflow.com/questions/31404566
复制相似问题