22,209
社区成员
发帖
与我相关
我的任务
分享
declare @in table
(enterprise varchar(8) not null,
date datetime not null,
money float null)
insert into @in
select '001','2007-01-01',40
union all
select '002','2007-02-01',100
declare @out table
(enterprise varchar(8) not null,
date datetime not null,
money float null)
insert into @out
select '001','2005-03-01',10
union all
select '001','2005-09-01',5
union all
select '001','2006-01-01',5
union all
select '001','2007-01-01',5
union all
select '002','2005-01-01',123
select a.enterprise ,a.date,b.date,in_money,out_money,a.date - b.date as [借款时限],in_money - out_money as money from
( select enterprise,max(year(date)) as date ,sum(money) as in_money from @in
group by enterprise
) a left join
(
select a.enterprise,a.date,sum(b.money) as out_money from
(select distinct enterprise enterprise,year(date) date from @out) a
left join @out b on year(b.date)>=a.date and a.enterprise = b.enterprise
group by a.enterprise,a.date
) b on a.enterprise = b.enterprise
(2 行受影响)
(5 行受影响)
enterprise date date in_money out_money 借款时限 money
---------- ----------- ----------- ---------------------- ---------------------- ----------- ----------------------
001 2007 2005 40 25 2 15
001 2007 2006 40 10 1 30
001 2007 2007 40 5 0 35
002 2007 2005 100 123 2 -23
(4 行受影响)
declare @in table
(enterprise varchar(8) not null,
date datetime not null,
money float null)
insert into @in
select '001','2007-01-01',40
union all
select '002','2007-02-01',100
declare @out table
(enterprise varchar(8) not null,
date datetime not null,
money float null)
insert into @out
select '001','2005-03-01',10
union all
select '001','2005-09-01',5
union all
select '001','2006-01-01',5
union all
select '001','2007-01-01',5
union all
select '002','2005-01-01',123
select a.enterprise ,a.date - b.date ,in_money - out_money as money from
( select enterprise,max(year(date)) as date ,sum(money) as in_money from @in
group by enterprise
) a left join
(
select a.enterprise,a.date,sum(b.money) as out_money from
(select distinct enterprise enterprise,year(date) date from @out) a
left join @out b on year(b.date)<=a.date and a.enterprise = b.enterprise
group by a.enterprise,a.date
) b on a.enterprise = b.enterprise