34,590
社区成员
发帖
与我相关
我的任务
分享
p p cs
---- ---- -----------
B A 30
A Z 20
D C 10
(3 行受影响)
with m as
(
select 'A' p ,'B' r,10 c union all
select 'A','Z',20 union all
select 'C','D',30 union all
select 'D','C',40 union all
select 'A','B',10 union all
select 'B','A',50
),
t as (
select p , r ,c from m where p> r
union all
select r , p , -c from m where p< r
),
result as
(select p ,r , SUM(c) cs from t group by p,r )
select
case when cs >0 then p else r end as p ,
case when cs <0 then p else r end as p ,
abs(cs) as cs
from result
if object_id('tempdb..#a','U') is not null
drop table #a
go
create table #a (payacno char(1),rcvacno char(1),amount tinyint)
insert into #a(payacno,rcvacno,amount)
values('A','B',10),
('A','Z',20),
('C','D',30),
('D','C',40),
('A','B',10),
('B','A',50);
with a as (
select *,row_number() over(partition by unicode(payacno)+unicode(rcvacno) order by amount desc) as rna
from #a
),
b as
(
select distinct payacno,rcvacno,sum(amount) over(partition by unicode(payacno)+unicode(rcvacno) order by amount desc) as sum_am
from a where rna <>1
)
select a.payacno,a.rcvacno,a.amount - isnull(b.sum_am,0) as amount
from a left outer join b on (unicode(a.payacno)+unicode(a.rcvacno))-(unicode(b.payacno)+unicode(b.rcvacno))=0
where a.rna = 1
/*
payacno rcvacno amount
------- ------- -----------
B A 30
D C 10
A Z 20
(3 行受影响)
*/
declare @tab table(payacno varchar(10),rcvacno varchar(10),amount int)
insert into @tab(payacno, rcvacno, amount)
select 'A', 'B', 10 union all
select 'A', 'Z', 20 union all
select 'C', 'D', 30 union all
select 'D', 'C', 40 union all
select 'A', 'B', 10 union all
select 'B', 'A', 50
;with sel as(
select payacno+rcvacno no1,sum(amount) as [amount], payacno,rcvacno
from @tab group by payacno,rcvacno
)
select a.payacno,a.rcvacno,a.amount-isnull(b.amount,0) as [amount] from sel a
left join sel b on a.no1=reverse(b.no1)
where a.amount-isnull(b.amount,0)>0
declare @tb table(payacno char(2),rcvacno char(2),amount int)
insert into @tb
select 'A','B',10 union all
select 'A','Z',20 union all
select 'C','D',30 union all
select 'D','C',40 union all
select 'A','B',10 union all
select 'B','A',50;
with cte as(
select payacno,rcvacno,sum(amount) as 'amount' from @tb group by payacno,rcvacno
)
select payacno=(case when amount<0 then rcvacno else payacno end),
rcvacno=(case when amount<0 then payacno else rcvacno end),
amount=abs(amount) from (
select payacno,rcvacno,amount=t1.amount-(select isnull(sum(amount),0) from cte t2 where t1.payacno=t2.rcvacno
and t2.payacno=t1.rcvacno) from cte t1 where payacno>rcvacno or not exists (select 1 from cte t2 where t1.payacno=t2.rcvacno
and t2.payacno=t1.rcvacno))t