SQL按条件累加表相应字段?
表A:
ID Date Client NoPay YesPay1 2012-02-01 张三 1000 02 2012-02-02 张三 0 5003 2012-02-03 张三 800 04 2012-02-02 李四 600 05 2012-02-02 李四 0 5006 2012-02-03 李四 0 100
ID Date Client NoPay YesPay Surplus1 2012-02-01 张三 1000 0 10002 2012-02-02 张三 0 500 5003 2012-02-03 张三 800 0 13004 2012-02-02 李四 600 0 6005 2012-02-02 李四 0 500 1006 2012-02-03 李四 0 100 0
--ID Date Client NoPay YesPay--1 2012-02-01 张三 1000 0--2 2012-02-02 张三 0 500--3 2012-02-03 张三 800 0--4 2012-02-02 李四 600 0--5 2012-02-02 李四 0 500--6 2012-02-03 李四 0 100if OBJECT_ID('tb')is not nulldrop table tbgo create table tb (ID int,Date datetime,Client varchar(50), NoPay int,YesPay int)insert into tb values(1 , '2012-02-01' , '张三' , 1000 , 0)insert into tb values(2 , '2012-02-02' , '张三' , 0 , 500)insert into tb values(3 , '2012-02-03' , '张三' , 800 , 0)insert into tb values(4 , '2012-02-02' , '李四' , 600 , 0)insert into tb values(5 , '2012-02-02' , '李四' , 0 , 500)insert into tb values(6 , '2012-02-03' , '李四' , 0 , 100)--ID Date Client NoPay YesPay Surplus--1 2012-02-01 张三 1000 0 1000--2 2012-02-02 张三 0 500 500--3 2012-02-03 张三 800 0 1300--4 2012-02-02 李四 600 0 600--5 2012-02-02 李四 0 500 100--6 2012-02-03 李四 0 100 0;with ct as (select *,(select SUM(NoPay-YesPay) from tb where ID=t.ID )s from tb t )select c.ID,c.Date,c.Client,c.NoPay,c.YesPay,(select SUM(s) from ct where Client=c.Client and Date<=c.Date and ID<=c.ID )Surplus from ct c ID Date Client NoPay YesPay Surplus----------- ----------------------- -------------------------------------------------- ----------- ----------- -----------1 2012-02-01 00:00:00.000 张三 1000 0 10002 2012-02-02 00:00:00.000 张三 0 500 5003 2012-02-03 00:00:00.000 张三 800 0 13004 2012-02-02 00:00:00.000 李四 600 0 6005 2012-02-02 00:00:00.000 李四 0 500 1006 2012-02-03 00:00:00.000 李四 0 100 0(6 行受影响)
[解决办法]
select id,date,client,nopay,yespay,(select sum(s) from (select *,(nopay-yespay)s from tb) t where t.id<=a.id and t.client=a.client) from (select *,(nopay-yespay)s from tb) a