SSRS报告

时间:2017-03-24 19:07:32

标签: date reporting-services sql-server-2012

我正在生成一份报告,其中我每月汇总价格和成本值。我想显示相同的时间段 - 1年。我不清楚如何嵌套这个。声明时我会使用一个案例吗?

我可怕的例子。

select month, cost, price from table1 where (define months here in SSRS parameter filter)

我想看看:

select month, cost, price, lastyearcost, lastyearprice FROM table1 where (define months here in SSRS parameter filter)

我知道我应该使用GETDATE()-1的一些变体,但这包括运行报告时传递的数据范围参数吗?如何选择成本列应用日期过滤器,然后获得去年该期间的成本结果?

希望这有道理吗?

1 个答案:

答案 0 :(得分:1)

一种方法是使用DATEPART()进行正确的嵌套和配对。

select 
    month, 
    cost, 
    price, 
    lastyearcost, 
    lastyearprice 
FROM table1 
where 
    --this is limiting the data to the year passed in, and the previous year
    (datepart(year,DateColumn) = @YearParam or datepart(year,DateColumn) = @YearParam-1)
    and 
    --this is limiting the months to the two parameters you pass in as integers
    (datepart(month,DateColumn) >= @minMonthParam and datepart(month,DateColumn) <= @maxMonthParam)

测试数据

请参阅D EMO HERE

declare @table1 table (DateColumn date)
insert into @table1 (DateColumn)
values
('1/1/2016'),
('2/1/2016'),
('3/1/2016'),
('4/1/2016'),
('5/1/2016'),
('6/1/2016'),
('7/1/2016'),
('8/1/2016'),
('9/1/2016'),
('10/1/2016'),
('11/1/2016'),
('12/1/2016'),
('1/1/2017'),
('2/1/2017'),
('3/1/2017'),
('4/1/2017'),
('5/1/2017')

declare @YearParam int = 2017
declare @minMonthParam int = 2
declare @maxMonthParam int = 5

select 
    DateColumn
FROM @table1 
where 
    (datepart(year,DateColumn) = @YearParam or datepart(year,DateColumn) = @YearParam-1)
    and 
    (datepart(month,DateColumn) >= @minMonthParam and datepart(month,DateColumn) <= @maxMonthParam)