[英]Sum over Partition By Only when Value is Greater than 0
我只想在另一個表中的分類帳金額為正時對申請金額求和
例子
表A
Statement # ID
500 1
500 2
500 3
500 4
表B
Ledger_Amount Type ID
-389.41 Credit 1
-1218.9 Credit 2
-243.63 Credit 3
3485.19 Invoice 4
表 C
Applied_Amount ID
389.41 1
1218.9 2
243.63 3
1633.25 4
目前的代碼是
(sum(applied_amount) over (partition by statement_number),0)
它總共得到 3485.19 美元,因為它僅按語句編號求和,並且所有 ID 都具有相同的語句編號,我希望它得出的值是 1633.25 美元,因為它不應該在表 B 中的 ledger_amount 中求和任何東西小於 0,因此不應將 ID 1、2、3 相加 只有有效值是 ID 4
有一種方法:
假設 ID 是一個唯一的列,首先我們應該根據 statementnumber 獲取我們要處理的 ID,並將它們保存在臨時表中:
select Id
into #Ids
from tableA
where StatementNumber=@yourStatementNumber
然后,剔除B表中為負數的ID
Select Id
into #IdsWithPositiveLedger
From #Ids
Where Id in (
Select ID
From tableB
Where Ledger_Amount>0
)
最后,使用剩下的 ID 來計算總和:
Select sum(applied_amount)
from tableC
where Id in (select Id from #IdsWithPositiveLedger)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.