if object_id('tb') is not null
drop table tb
go
create table tb (GroupID varchar(4) ,EveryPrice int ,TotolPrice int )
insert into tb
select 'A','20','100' union all
select 'B','10','500' union all
select 'B','30','500' union all
select 'C','30','400' union all
select 'C','20','400' union all
select 'C','600','400'
go
select * from tb
-- 涉及累减的计算 ,总价价格-减去单笔价格, 期待结果如下。
--能不用游标和临时表最好
--GroupID EveryPrice TotolPrice Leave
--A 20 100 80
--B 10 500 490
--B 30 500 460
--C 30 400 370
--C 20 400 350
--C 600 400 -250------解决思路----------------------
GroupID EveryPrice TotolPrice id leave
------- ----------- ----------- ----------- -----------
A 20 100 1 80
B 10 500 1 490
B 30 500 2 460
C 30 400 1 370
C 20 400 2 350
C 600 400 3 -250
------解决思路----------------------
试一下下面的sql
with cte as
(
select *,ROW_NUMBER() over(partition by GroupID order by GroupID ) as rId from tb11
)
select GroupID,EveryPrice,TotolPrice,
(TotolPrice-EveryPrice-isnull((select SUM(EveryPrice)
from cte where GroupID=aa.GroupID and rId<aa.rID ),0)) as leave from cte as aa