SSRS月度/每日报告

时间:2015-07-20 20:38:14

标签: sql-server tsql reporting-services

我的报告中有一个变量,它包含两个可能的值:'每月'和'每日'。我怎么能把这个变量(让我们称之为@reportModel)。我认为它应该在GROUP BY子句的某个地方,但不知道它应该是什么样的。

DECLARE @reportModel VARCHAR(10)
SET @reportModel = 'monthly'

SELECT P.product, SUM(O.price * O.quantity), O.orderDate
FROM Products AS P
INNER JOIN Orders AS O ON P.ID = O.ID

现在怎么办?

4 个答案:

答案 0 :(得分:0)

如何处理存储过程,如......

CREATE PROCEDURE rpt_GetData
  @reportModel VARCHAR(10)
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @Sql NVARCHAR(MAX);

IF (@reportModel = 'daily')
  BEGIN
   SET @Sql = N' SELECT P.product
                       , SUM(O.price * O.quantity) AS Total
                       , O.orderDate
                FROM Products AS P
                INNER JOIN Orders AS O ON P.ID = O.ID
                GROUP BY P.product , O.orderDate' 
     Exec sp_executesql @Sql
  END
ELSE IF (@reportModel = 'monthly')
  BEGIN
       SET @Sql = N' SELECT P.product
                          , SUM(O.price * O.quantity) AS Total
                          , MONTH(O.orderDate) AS [Month]
                    FROM Products AS P
                    INNER JOIN Orders AS O ON P.ID = O.ID
                    GROUP BY P.product, MONTH(O.orderDate)'
     Exec sp_executesql @Sql            
  END

END

答案 1 :(得分:0)

我会把它放在表格或图表的表达式中,而不是在查询中进行。

=IIF(Parameters!reportModel.Value = "monthly", Month(Fields!orderDate.Value), Fields!orderDate.Value)

如果您更愿意在查询中执行此操作并且不想等待DBA绕过部署存储过程(更不用说在任何更改时保留它),可以在CASE中使用您的参数:

SELECT P.product, SUM(O.price * O.quantity),  
CASE WHEN @reportModel = 'monthly' THEN CAST(MONTH(O.orderDate) AS VARCHAR(12)) 
     ELSE CAST(O.orderDateAS VARCHAR(12)) END AS DT
FROM    WORKFLOW_SHARED.MAIN.VW_CLAIMSOVERPAYMENT
WHERE DATECOMPLETED > '7/1/2015'
GROUP BY P.product, 
CASE WHEN @reportModel = 'monthly' THEN CAST(MONTH(O.orderDate) AS VARCHAR(12)) 
     ELSE CAST(O.orderDateAS VARCHAR(12)) END

这样您就不必维护两份单独的报告。

答案 2 :(得分:0)

将此作为答案添加,因为我在@ M.Ali的回答中提到了这一点。

所以我建议你用其中一个选项稍微改变思路。

  1. 两份报告 - 只需每天报告一次,另一份报告每月报告一次。现在您不必担心复杂的SQL等。
  2. 制作2个存储过程,每天一个GROUP BY,每月一个。然后在您的SSRS数据集中,为您创建一个表达式SQL,它根据参数选择过程:

    =IIf(Parameters!reportModel.Value = "monthly", "GetMonthlyData", "GetDailyData")
    

答案 3 :(得分:-1)

如此简单的事情

select 
    P.product
    ,Total = sum(O.price * O.quantity)
    , O.orderDate
from 
    Products as P
    inner join Orders as O on P.ID = O.ID
where
    @reportModel = 'daily'

union all

select 
    P.product
    ,Total = sum(O.price * O.quantity)
    ,[Month] = MONTH(O.orderDate)
from 
    Products as P
    inner JOIN Orders as O on P.ID = O.ID
group by
    P.product
    ,[Month] = MONTH(O.orderDate)
where
    @reportModel = 'monthly'