我想要的是什么:我想要一个结果集,告诉我10年之前和今年之后的10年。
示例:因为今年是2014年:
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
我尝试了什么:我不是一个庞大的SQL人,所以请耐心等待我:
SELECT
YEAR(DATEADD(year, -10, GETDATE())) AS prevYear,
YEAR(DATEADD(year, 10, GETDATE())) AS nextYear,
YEAR(GETDATE()) AS currentYear
WHERE currentYear BETWEEN prevYear AND nextYear
有人可以帮帮我吗?我甚至关闭了吗?
答案 0 :(得分:6)
SELECT TOP (21) YEAR(DATEADD(YEAR, number-10, GETDATE()))
FROM master.dbo.spt_values WHERE type = N'P' ORDER BY number;
您可能希望使用此数据执行其他操作。一个示例可能是聚合来自某个表的数据,并包括此表中未找到的此范围内的年份。以下是您可以这样做的方式:
;WITH y(d) AS
(
SELECT TOP (21) DATEADD(YEAR, number-10, DATEADD(YEAR, YEAR(GETDATE())-1900,0))
FROM master.dbo.spt_values WHERE type = N'P' ORDER BY number
)
SELECT y.d, COUNT(o.key)
FROM y
LEFT OUTER JOIN dbo.other_table AS o
ON o.datetime_column >= d.d
AND o.datetime_column < DATEADD(YEAR, 1, d.d)
GROUP BY y.d
ORDER BY y.d;
答案 1 :(得分:2)
假设您需要从现有表中获取这些记录:
declare @thisYear int = year(getdate())
select yourYear
from table1
where yourYear between @thisYear -10 and @thisYear + 10
and yourYear <> @thisYear --Assuming you don't need the current year