34,590
社区成员
发帖
与我相关
我的任务
分享
SELECT hth,cdate,(SELECT SUM(sl) FROM A WHERE hth=t.hth AND cdate<=t.cdate)-(SELECT SUM(sl) FROM B WHERE hth=t.hth AND cdate<=t.cdate) sl1 FROM A AS t
UNION ALL
SELECT hth,cdate,(SELECT SUM(sl) FROM A WHERE hth=t.hth AND cdate<=t.cdate)-(SELECT SUM(sl) FROM B WHERE hth=t.hth AND cdate<=t.cdate) sl1 FROM B AS t
ORDER BY hth,cdate
select hth, cdate, sl from A
union all
select hth, cdate, sl from B
order by 1,2
--随便写了个,可以继续优化:
create table #input
(hth char(3),
cdate datetime,
sl int
)
insert into #input
select '001','2016-9-1',3000 union all
select '002','2016-9-1',200
go
create table #output
(hth char(3),
cdate datetime,
sl int
)
go
insert into #output
select '001','2016-9-2',1000 union all
select '002','2016-9-3',20
select i.* from #input as i join #output as o on i.hth=o.hth union all
select o.hth,o.cdate,i.sl-o.sl from #input as i join #output as o on i.hth=o.hth
order by i.hth,i.cdate