SQL/Report Builder-基于某些多个月条目返回数据的报告
我需要创建一个报告,根据每个季度的打开日期和一个月内打开的所有记录返回一系列数据 因此,如果我在8月初运行该报告,它将显示开放日期在5月、2月、11月和8月之间的记录,对年份没有限制。打开日期月份将由运行报告的月份定义 我有这个非常基本的代码SQL/Report Builder-基于某些多个月条目返回数据的报告,sql,sql-server,date,reporting-services,monthcalendar,Sql,Sql Server,Date,Reporting Services,Monthcalendar,我需要创建一个报告,根据每个季度的打开日期和一个月内打开的所有记录返回一系列数据 因此,如果我在8月初运行该报告,它将显示开放日期在5月、2月、11月和8月之间的记录,对年份没有限制。打开日期月份将由运行报告的月份定义 我有这个非常基本的代码 SELECT RecordMonth, RecordYear, caseRef, caseDescription, caseOpenDate, caseClosedDate, PersonName, PersonSurname FROM
SELECT RecordMonth, RecordYear, caseRef, caseDescription,
caseOpenDate, caseClosedDate, PersonName, PersonSurname
FROM dbo.casereview
WHERE month(caseopendate) = 03
OR month(casecopendate) = 06
OR month(caseopendate) = 09
OR month(caseopendate) = 12
问题是,我需要动态运行它,因此无论运行哪个月,它都可以显示开放日期在前几个季度/月内的情况。您可以使用模来根据当前系统日期计算所需的4个月数字,然后根据这些数字进行过滤 在你的情况下,像这样的事情会起作用
DECLARE @month int = month(getdate())
DECLARE @m1 int = ((@month -1 ) % 12) +1
DECLARE @m2 int = ((@month + 2) % 12) +1
DECLARE @m3 int = ((@month + 5) % 12) +1
DECLARE @m4 int = ((@month + 8) % 12) +1
SELECT RecordMonth, RecordYear, caseRef, caseDescription,
caseOpenDate, caseClosedDate, PersonName, PersonSurname
FROM dbo.casereview
WHERE month(caseopendate) IN (@m1, @m2, @m3, @m4)
因此,首先要获取当前月号,我们使用getdate()
获取当前日期,使用month
函数仅返回月号。所以今天这等于8
接下来,我们使用模(即%
符号)计算出我们需要的月份。
例如,如果月份=6,那么@m4计算为
(@month+8)=14
14%12=2(14的剩余部分除以12)
2+1=3
注意:我已经把它做得比需要的长了一点,所以它更容易阅读。我们可以将@m1、@m2等的计算直接放入select语句中,但单独这样做会更清楚。
注意,我在语句中使用了一个
,而不是在WHERE
子句中使用了一堆或s<
中的code>仅匹配括号中列出的任何值。假设您希望所有匹配行按opendate顺序排列,我们可以简单地使用模函数。我们可以进行四次MONTH%12
查询,或者一次MONTH%3
查询
我构建了一个测试数据库来显示基本过程:
create database [_TEST_QUARTERS];
GO
USE [_TEST_QUARTERS];
GO
create table [CASEREVIEW] (
[CASE_ID] integer primary key,
[CASEOPENDATE] date
);
insert into [CASEREVIEW] values ( 1, '2016-09-19');
insert into [CASEREVIEW] values ( 2, '2016-10-20');
insert into [CASEREVIEW] values ( 3, '2016-11-11');
insert into [CASEREVIEW] values ( 4, '2016-12-22');
insert into [CASEREVIEW] values ( 5, '2017-01-11');
insert into [CASEREVIEW] values ( 6, '2017-02-12');
insert into [CASEREVIEW] values ( 7, '2017-03-13');
insert into [CASEREVIEW] values ( 8, '2017-04-14');
insert into [CASEREVIEW] values ( 9, '2017-05-15');
insert into [CASEREVIEW] values (10, '2017-06-16');
insert into [CASEREVIEW] values (11, '2017-07-17');
insert into [CASEREVIEW] values (12, '2017-08-18');
因此,我们可以看到它必须从中选择的数据:
select CURRENT_TIMESTAMP as [Today];
select * from [CASEREVIEW];
以及实际查询:
select [CASE_ID], [CASEOPENDATE] from [CASEREVIEW]
where MONTH(CONVERT(VARCHAR(10), [CASEOPENDATE], 120)) % 3 = MONTH(CONVERT(VARCHAR(10), CURRENT_TIMESTAMP, 120)) % 3
ORDER BY [CASEOPENDATE];
结果:
CASE_ID CASEOPENDATE
----------- ------------
3 2016-11-11
6 2017-02-12
9 2017-05-15
12 2017-08-18
(4 row(s) affected)
哎呀,你在我写代码的时候发帖了。啊,嗯。你的更干净;虽然我特别试图避免使用变量,以防这对querent很重要。