如何为我的案例实现存储过程?

时间:2018-10-30 00:36:39

标签: sql sql-server stored-procedures reporting-services

我将使用一张表中的以下数据记录来实现SSRS摘要数据报告。

ID         Part                 Type                Value
------------------------------------------------------------
1          Payroll              State Tax           2010
1          Payroll              City Tax             500
1          Payroll              Medical              300
2          Payroll              State Tax           2000
2          Payroll              City Tax             400
3          Payroll              FICA                 200
1          Refund               State Tax           -500
1          Refund               Medical             -100
3          Payroll              FICA                 200
1          Refund               State Tax           -500
1          Refund               Medical             -100

我如何实现一个存储过程以通过为每个零件加总相同的Type值来产生以下结果,从而易于构建SSRS报告?非常感谢!

Type                      Payroll                  Refund                 Total
State Tax                 4010                      -500                  3600
City Tax                  900                        0                    900
FICA                      400                        0                    400
Medical                   300                       -100                  200

2 个答案:

答案 0 :(得分:2)

您可以将CTE /子查询与条件聚合一起使用

CREATE PROCEDURE YourProcName
AS
    SET NOCOUNT ON;
    WITH CTE AS
    (
       SELECT Type,
              SUM(CASE WHEN Value > 0 THEN Value ELSE 0 END) payroll,
              SUM(CASE WHEN Value < 0 THEN Value ELSE 0 END) refund
       FROM YourTable
       GROUP BY Type
    )
    SELECT CTE.*,
           CTE.payroll + CTE.refund Total
    FROM CTE;
GO;

答案 1 :(得分:1)

您可以使用条件聚合:

select type,
       sum(case when part = 'Payroll' then value else 0 end) as payroll,
       sum(case when part = 'Refund' then value else 0 end) as refund
from t
group by type;

当简单查询执行所需操作时,为什么要存储过程?我强烈建议您使用视图或表值函数。