在 SQL 中,如何基于以“”开头的字段创建运行总计?

问题描述 投票:0回答:2

我是一个 sql 新手,正在开发一个程序,我试图根据用户输入的三个字段(Deduction PayCodeCat 和 EmployeeID)捕获运行总计,但是如果员工不在表中,则运行总计列开始时为空。

简化程序:

更改程序 [dbo].[2023_ClaimsInsert] (

@PayCodeCat NVARCHAR(3) ,
@EmployeeID INT ,
@扣除FLOAT )

AS 开始 不设置计数;

插入.dbo。[2023_ClaimsTable] (
支付码猫 , 员工ID ,
扣除 ,
QW_运行平衡 ,
AS_运行平衡 ,
ZX_运行平衡 )

价值观 (@PayCodeCat ,
@员工ID ,
@扣除 ,
(SELECT sum(Deduction)+@Deduction FROM 2023_ClaimsTable CL WHERE @PayCodeCat = 'QW' AND @EmployeeID = CL.EmployeeID) ,
(SELECT SUM(扣除)+@Deduction FROM 2023_ClaimsTable CL WHERE @PayCodeCat = 'AS' AND @EmployeeID = CL.EmployeeID) ,
(SELECT SUM(扣除)+@Deduction FROM 2023_ClaimsTable CL WHERE @PayCodeCat = 'ZX' AND @EmployeeID = CL.EmployeeID)

这些是结果,只要员工是新加入表的,运行余额就会从 Null 开始。

员工ID 支付码猫 扣除 QW_运行平衡 AS_运行平衡 ZX_运行平衡
1 AS 100
1 AS 200 300
1 AS 800 1100
2 AS 700
2 AS 200 900
1 QW 200 200 1100

我尝试修改值语句以包含 OR IS Null

  • (从 AP_2023_ClaimsTable CL 中选择总和(扣减)+@Deduction,其中 @PayCodeCat = 'AP' AND (@EmployeeID = CL.EmployeeID OR CL.EmployeeID IS NULL))

根据我在其他 stackoverflow 答案中发现的内容,我尝试使用 Exists 和 Notists 以及 case 语句,但我只是破坏了代码。

sql procedure cumulative-sum
2个回答
0
投票

请使用以下查询来获取结果,

SELECT EmployeeID, PayCodeCat, Deduction,
        CASE WHEN PayCodeCat = 'AS' THEN SUM(Deduction) over (Partition by EmployeeID, PayCodeCat Order by rn) END AS AS_RunningBalance,
        CASE WHEN PayCodeCat = 'QW' THEN SUM(Deduction) over (Partition by EmployeeID, PayCodeCat Order by rn) END AS QW_RunningBalance,
        CASE WHEN PayCodeCat = 'ZX' THEN SUM(Deduction) over (Partition by EmployeeID, PayCodeCat Order by rn) END AS ZX_RunningBalance
FROM (
    SELECT *,
            ROW_NUMBER() over (order by EmployeeID, PayCodeCat) as rn
    FROM 2023_ClaimsTable
) a

0
投票

假设您只想将

@Deduction
应用于与 @PayCodeCat 匹配的
Running Balance
,我认为您的代码看起来会更好,如下所示:

ALTER Procedure [2023_ClaimsInsert] (
      @PayCodeCat   nvarchar(3)
    , @EmployeeID   int
    , @Deduction    float
    ) as
begin
    set nocount on
    insert into [2023_ClaimsTable] (
          PayCodeCat
        , EmployeeID
        , Deduction
        , QW_RunningBalance
        , AS_RunningBalance
        , ZX_RunningBalance
        )
    select
          @PayCodeCat
        , @EmployeeID
        , @Deduction
        , nullIf(
            (select isNull(SUM(Deduction), 0) from [2023 _ClaimsTable]
              where EmployeeID = @EmployeeID and PayCodeCat = 'QW' )
            + case @PayCodeCat when 'QW' then @Deduction else 0 end, 0)
        , nullIf(
            (select isNull(SUM(Deduction), 0) from [2023 _ClaimsTable]
              where EmployeeID = @EmployeeID and PayCodeCat = 'AS' )
            + case @PayCodeCat when 'AS' then @Deduction else 0 end, 0)
        , nullIf(
            (select isNull(SUM(Deduction), 0) from [2023 _ClaimsTable]
              where EmployeeID = @EmployeeID and PayCodeCat = 'ZX' )
            + case @PayCodeCat when 'ZX' then @Deduction else 0 end, 0)
end
© www.soinside.com 2019 - 2024. All rights reserved.