Select Code,Date,Payment_Total=(Select Total=IsNull(Sum(Payment),0) From tem as a  where a.Date<=b.Date and a.Code=b.code) from tem as b