【发布时间】:2021-07-01 20:51:34
【问题描述】:
with cte as
(
select trd_nbr,[date],sum(case when txn_typ='A' then abs(amount) else 0 end)
amountforA,
sum(case when txn_typ='B' then abs(amount) else 0 end) amountforB,
sum(case when txn_typ='C' then abs(amount) else 0 end) amountforC
from table1
group by trd_nbr,[date]
)
select trd_nbr,[date],
(case when amountforA=amountforB and amountforB=amountforC then amountforC
else amountforA-amountforC end) Amount,
(case when amountforA=amountforB and amountforB=amountforC then 'M' else
'NM' end) Matched
from cte WHERE amountforA>0 and amountforB>0 and amountforC>0
如何将上述查询用于存储过程
create proc proc name()
begin
select amount, matched ,...from table1
where condition..
union all
select column1, column2.... from table2
where condition..
end;
这里的数量和匹配列取自 with 子句。如何使用它..
【问题讨论】:
-
对于这两种情况,您都提到了
same logic for C and B。你能举一些C and B的例子吗?也请展示你的尝试 -
是的,如果 B 和 C 的记录公共列和总金额匹配,则单独显示 c。如果不匹配,则 B-C。
-
你需要展示你的预期结果和你的尝试。
-
场景 1 输出:C 金额 = 4000,单行显示交易编号 1 场景 2 输出:C 金额 = 10000-5000 = 5000,单行显示交易编号 2 C 金额 = 6000-2000 = 4000 单行交易号 3
标签: sql sql-server