我有一个应用程序无法在下拉列表中显示2016年以后的任何一年。
与此同时,随着时间的推移,我需要展示过去几年。
例如:
所以我开发了以下代码来实现这一目标。
您是否知道在TSQL中实现此目的的更好方法?
SELECT [Year] FROM (
SELECT YEAR(GETDATE()) AS 'Year'
UNION
SELECT YEAR(DATEADD(year,-1,GETDATE())) AS 'Year' WHERE YEAR(GETDATE()) > 2017
UNION
SELECT YEAR(DATEADD(year,-2,GETDATE())) AS 'Year' WHERE YEAR(GETDATE()) > 2018
UNION
SELECT YEAR(DATEADD(year,-3,GETDATE())) AS 'Year' WHERE YEAR(GETDATE()) > 2019
UNION
SELECT YEAR(DATEADD(year,-4,GETDATE())) AS 'Year' WHERE YEAR(GETDATE()) > 2020
UNION
SELECT YEAR(DATEADD(year,-5,GETDATE())) AS 'Year' WHERE YEAR(GETDATE()) > 2021
UNION
SELECT YEAR(DATEADD(year,-6,GETDATE())) AS 'Year' WHERE YEAR(GETDATE()) > 2022
UNION
SELECT YEAR(DATEADD(year,-7,GETDATE())) AS 'Year' WHERE YEAR(GETDATE()) > 2023
) x
ORDER BY [Year] DESC
答案 0 :(得分:3)
试试这个,这将生成从2016年到当年的年份列表
WITH CTE_TEST AS(
SELECT 2016 AS NYEAR
UNION ALL
SELECT NYEAR+1
FROM CTE_TEST
WHERE NYEAR+1 <= YEAR(GETDATE())
)
SELECT * FROM CTE_TEST
答案 1 :(得分:1)
创建一个Year表,其中包含您希望应用程序处理的所有有效年份。
Select Year From Year
Where Year>=2016
AND Year<=DATEPART(Year,GETDATE())
答案 2 :(得分:1)
是的,使用日历表很简单:
SELECT [Year] = YEAR(c.Date)
FROM CalendarTable c
WHERE YEAR(c.Date) >= 2016 AND YEAR(c.Date) <= YEAR(GETDATE())
GROUP BY YEAR(c.Date)
ORDER BY YEAR(c.Date)
How to generate a calendar table(寻找“日历表”)。
答案 3 :(得分:1)
您可以创建和使用这样的内联数字表:
-- Return all years starting from current year up to @YEAR
DECLARE @YEAR INT = 2011
SELECT y AS 'YEAR'
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1
FROM (VALUES (0), (0), (0), (0), (0) ) AS t1(n)
CROSS JOIN (VALUES (0), (0), (0), (0), (0) ) AS t2(n)) AS x(i)
CROSS APPLY (SELECT YEAR(DATEADD(year,-1*x.i,GETDATE()))) AS t(y)
WHERE y >= @YEAR
上述查询使用的内联表包含5x5 = 25行。您可以根据自己的实际需要进行调整。