我有一个报告,我每季度运行一次(在SQL Server Management Studio 2011中),该报告从按年份和按季度组织的表中提取数据。我通常在每次运行时手动更新查询,但我想尝试使其尽可能自动化以供将来用户使用。
以下是我目前用于选择所需日期范围的代码:
WHERE
(CASE
WHEN AN.[Year] = 2016 AND AN.[Quarter] IN (1,2) THEN 1
WHEN AN.[Year] = 2015 AND AN.[Quarter] IN (3,4) THEN 1
ELSE 0 END) = 1
因此,每运行一次查询,我手动更新所有where子句以反映所需的日期范围。
我还需要提取数据滚动3年和去年的季度。以下是我目前正在使用的内容:
WHERE
(CASE
WHEN Al.[Year] = 2016 AND Al.[Quarter] IN (1,2) THEN 1
WHEN Al.[Year] IN (2014,2015) THEN 1
WHEN Al.[Year] = 2013 AND Al.[Quarter] in (3,4) THEN 1
ELSE 0 END) = 1
WHERE
(CASE
WHEN AN.[Year] = 2015 AND AN.[Quarter] = 2 THEN 1
ELSE 0 END) = 1
有没有办法自动化这个,以便有人可以打开查询,点击执行,并获取所需日期范围的数据?
答案 0 :(得分:0)
利用DATEPART,利用当前年度和当前季度优势。以下查询可以根据需要构建多年
DECLARE @tblDates TABLE
(
Dt Date,
[Year] int,
[Quarter] int
)
--Identify the boundary condition
DECLARE @CurrentQuarter INT
SET @CurrentQuarter = (SELECT DATEPART(QQ, GETDATE()))
--Add in some test data
INSERT INTO @tblDates
SELECT GETDATE(), DATEPART(YY, GETDATE()), DATEPART(QQ, GETDATE())
UNION SELECT DATEADD(QQ, -1, GETDATE()), DATEPART(YY, DATEADD(QQ, -1, GETDATE())), DATEPART(QQ, DATEADD(QQ, -1, GETDATE()))
UNION SELECT DATEADD(QQ, -2, GETDATE()), DATEPART(YY, DATEADD(QQ, -2, GETDATE())), DATEPART(QQ, DATEADD(QQ, -2, GETDATE()))
UNION SELECT DATEADD(QQ, -3, GETDATE()), DATEPART(YY, DATEADD(QQ, -3, GETDATE())), DATEPART(QQ, DATEADD(QQ, -3, GETDATE()))
UNION SELECT DATEADD(QQ, -4, GETDATE()), DATEPART(YY, DATEADD(QQ, -4, GETDATE())), DATEPART(QQ, DATEADD(QQ, -4, GETDATE()))
UNION SELECT DATEADD(QQ, -5, GETDATE()), DATEPART(YY, DATEADD(QQ, -5, GETDATE())), DATEPART(QQ, DATEADD(QQ, -5, GETDATE()))
UNION SELECT DATEADD(QQ, -6, GETDATE()), DATEPART(YY, DATEADD(QQ, -6, GETDATE())), DATEPART(QQ, DATEADD(QQ, -6, GETDATE()))
UNION SELECT DATEADD(QQ, -7, GETDATE()), DATEPART(YY, DATEADD(QQ, -7, GETDATE())), DATEPART(QQ, DATEADD(QQ, -7, GETDATE()))
SELECT * FROM @tblDates
WHERE
(
--This year, but prior to the current quarter
[Year] = DATEPART(YY, GETDATE()) AND [Quarter] < @CurrentQuarter
)
OR
(
--Last year, but greater than or equal to current quarter will book-end the last 4 quarters
[Year] = DATEPART(YY, GETDATE()) - 1 AND [Quarter] >=@CurrentQuarter
)