通过select中带case语句的参数过滤where子句

时间:2015-01-18 08:22:56

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

我的SELECT中有一个case语句,如下所示:

CASE
  when ((DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 > 2) AND (DATEDIFF(yy,u.birthday,GETDATE()) < 18)) then 'Yes'
  when ((DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 > 5) AND (DATEDIFF(yy,u.birthday,GETDATE()) >= 18) AND u.source <> 4) then 'Yes'
  when (DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 < 2) then 'No'
  else 'No'
end as [Retake Photo]

如何传递将过滤显示内容的报告参数(是,否或全部)?我在WHERE子句中需要一些东西,它可以引用select语句中确定的内容。

我正在使用SQL Server 2012 Reporting Services并在Visual Studio 2013中开发我的SSRS报告。

感谢您提供有关如何完成此任务的任何建议。我创建这些报告还是比较新的。

3 个答案:

答案 0 :(得分:2)

case重写为where子句或将完整查询放入子查询中

select * from
(
    select 
    CASE
      when ((DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 > 2) AND (DATEDIFF(yy,u.birthday,GETDATE()) < 18)) then 'Yes'
      when ((DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 > 5) AND (DATEDIFF(yy,u.birthday,GETDATE()) >= 18) AND u.source <> 4) then 'Yes'
      when (DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 < 2) then 'No'
      else 'No'
    end as [Retake Photo]
    from your_table
) tmp
where [Retake Photo] = 'Yes'

答案 1 :(得分:0)

尝试将此添加到WHERE子句

假设您为Yes,No,All传入的参数称为@Value

WHERE (@Value = 'All' OR 
@Value = 
    CASE
        WHEN ((DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 > 2) AND (DATEDIFF(yy,u.birthday,GETDATE()) < 18)) then 'Yes'
        WHEN ((DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 > 5) AND (DATEDIFF(yy,u.birthday,GETDATE()) >= 18) AND u.source <> 4) then 'Yes'
        WHEN (DATEDIFF(dd,ecf.uploadDate,GETDATE())/365.23076923074 < 2) then 'No'
        ELSE 'No'
    END )

您还可以在SSRS本身中为结果添加过滤器,但这样做效率较低,因为所有记录都将被提取并返回给客户端,然后才会应用过滤器。 / p>

要执行此操作,请右键单击控件(Tablix属性或您正在使用的控件),从左侧选择“过滤器”,然后添加过滤器。

答案 2 :(得分:0)

保持原始查询就像你写的那样(差不多):

CASE
  when DateDiff(yy, ecf.uploadDate, GETDATE()) > 2
    AND DateDiff(yy, u.birthday, GetDate()) < 18 then 'Yes'
  when DateDiff(dd, ecf.uploadDate, GETDATE()) > 5
    AND DateDiff(yy, u.birthday, GetDate()) >= 18
    AND u.source <> 4 then 'Yes'
  else 'No'
end as [Retake Photo]

只需将其设为CTE并过滤:

with
Q1 as(
   -- your original query
)
select  *
from    Q1
where   @Value = 'All'
    or  @Value = [Retake Photo];