Sql server SQL参数,用于检查过滤器在过去3、6、9个月或一年内返回的记录
我试图编写一个只返回过去3、6、9个月或一年的数据的存储过程。如果拉动8/15,则需要整整一个月;最近一次是7月 到目前为止,我已经能够找到如何找出前一个月的第一天和最后一天Sql server SQL参数,用于检查过滤器在过去3、6、9个月或一年内返回的记录,sql-server,reporting-services,parameters,ssrs-2014,Sql Server,Reporting Services,Parameters,Ssrs 2014,我试图编写一个只返回过去3、6、9个月或一年的数据的存储过程。如果拉动8/15,则需要整整一个月;最近一次是7月 到目前为止,我已经能够找到如何找出前一个月的第一天和最后一天 SELECT DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0))as 'First day of the month', DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) as 'Last day of the
SELECT DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0))as 'First day of the month',
DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) as 'Last day of the month'
需要检查的字段是TransactionDateKey ie 20161222。我想我应该在这个领域使用演员阵容,只检查每月和每天ie 201612,但我可能是错的。下面是一个粗略的模型,我认为我应该根据这个模型进行查询,但没有硬编码的日期
select FirstName + ' ' + LastName as 'Specialist',
empID as 'empID',
count(fact.spKey) as 'Count',
CAST(LEFT(CAST(TransactionDateKey AS VARCHAR(100)), 6) AS INT) as 'Month'
from Final.DimSpecialist s
inner join Final.FactTreatmentDay fact
on fact.spKey = s.spKey
where TransactionDateKey between 20161201 and 20161231
group by FirstName + ' ' + LastName,
empID,
CAST(LEFT(CAST(TransactionDateKey AS VARCHAR(100)), 6) AS INT)
如何声明单个参数@MonthRange,并在WHERE子句中使用它仅返回过去3个月、6个月、9个月或一年的数据?我认为需要将参数放置在-1位于“每月第一天”的位置。我认为还应该有一个case语句来检查4个可能的参数值中的每一个,但我不确定它应该放在哪里。如果您有任何建议,我将不胜感激。我相信有一些有趣的方法可以使用日期维度表来确定计算日期。如果您有yearmo字段,我选择提供一个与您已有答案非常匹配的答案,如果您没有这样的表,则适用:-
declare @months_to_report int; --procedure parameter
--Validation
if @months_to_report not in (3, 6, 9, 12) raiserror('Months to report must be one of 3, 6, 9, or 12.', 18, 1);
--Variables
declare @first date, @start date, @end date, @start_key int, @end_key int;
set @first = DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0)); --first day of previous month
set @end = DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)); --last day of previous month
set @start = DATEADD(M, 1 - @months_to_report, @first); --move back n-1 months to account for including previous month
set @start_key = Year(@start) * 10000 + Month(@start) * 100 + Day(@start); --start date as keys
set @end_key = Year(@end) * 10000 + Month(@end) * 100 + Day(@end); --end date as keys
select @first as 'First day of the month', @start as 'First day of reporting period', @end as 'Last day of the month/reporting period', @start_key as 'Start key', @end_key as 'End key';
此代码假定传递的参数为@months\u to\u report。我更喜欢验证存储过程中的参数。结束选择仅用于调试目的。您可以修改所提供的示例代码以遵循此步骤,并为硬编码日期补充@start_key和@end_key