我有一个表mes_transaction
,其中有变量dc
-它是 DEBIT 或 CREDIT 。我正在为另一个表编写sql过程(如果可以这样说)。在另一个表mes_aggregated_trx
中,我有trx_amt
-交易金额变量。基本上,我需要做的是编写一个过程,该过程基于trx_amt
中的mes_aggregated_trx
将dc
中的mes_transaction
加起来。
它需要看起来像这样(伪代码):
如果dc ='CREDIT',则添加ADDTOSUM(trx_amt)ELSE SUBFROMSUM(trx_amt)
我不知道如何在sql中实现IF子句。或者,也许我应该做一些事情,例如求和CREDIT trx_amt,然后求和DEBIT trx_amt,然后减去总和以获得所需的结果?但问题在于该过程如下所示:
$BODY$
BEGIN
INSERT INTO mes_aggregated_trx(pos_id
,mes_account_id
,merchant_code
,trx_count
,fee_amount
,trx_amount
,date)
SELECT pos_id
,mes_account_id
,merchant_code as location_id
,count(1) as count
,sum(comm_amt) as fee_amount
,sum(trx_amt) as trx_amount
,aggregation_date
FROM mes_transaction
WHERE post_date =aggregation_date
AND bic = aggregation_bic
AND rec_type='TRX'
AND (status='OK' OR status='OVR')
GROUP BY pos_id, merchant_code, mes_account_id
ON CONFLICT (date, merchant_code, pos_id, mes_account_id)
DO UPDATE
SET trx_count = excluded.trx_count
,trx_amount = excluded.trx_amount
,fee_amount = excluded.fee_amount;
-- Conflicts shouldn't happen since before insert new trx for date everything
-- for that date is cleaned, but to be 100% sure not to duplicate date, newest
-- date is stored.
RETURN 1;
END;
$BODY$
因此,我将需要以某种方式重做该过程的整个结构,而我对此并不十分了解。因此,任何帮助,技巧或建议都将非常有用!谢谢
答案 0 :(得分:2)
IF dc = 'CREDIT' THEN ADDTOSUM(trx_amt) ELSE SUBFROMSUM(trx_amt)
在SQL中将类似于:
SUM(CASE WHEN dc='CREDIT' THEN trx_amt ELSE -(trx_amt) END)