日期:2014-05-18 浏览次数:20652 次
表t1 账号 日期 收入 支出 A1 2011/6/10 200 0 A1 2012/6/11 0 100 A2 2012/6/10 100 0 A2 2012/6/11 100 0 A1 2012/6/14 0 100 A1 2012/6/15 300 0 表t2 账号 日期 今日余额 A1 2011/6/10 A1 2012/6/11 A2 2012/6/10 A2 2012/6/11 A1 2012/6/14 A1 2012/6/15
----------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2012-06-15 11:34:31
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------
--> 测试数据:[t1]
if object_id('[t1]') is not null drop table [t1]
go
create table [t1]([账号] varchar(2),[日期] datetime,[收入] int,[支出] int)
insert [t1]
select 'A1','2011/6/10',200,0 union all
select 'A1','2012/6/11',0,100 union all
select 'A2','2012/6/10',100,0 union all
select 'A2','2012/6/11',100,0 union all
select 'A1','2012/6/14',0,100 union all
select 'A1','2012/6/15',300,0
--> 测试数据:[t2]
if object_id('[t2]') is not null drop table [t2]
go
create table [t2]([账号] varchar(2),[日期] datetime,[今日余额] sql_variant)
insert [t2]
select 'A1','2011/6/10',null union all
select 'A1','2012/6/11',null union all
select 'A2','2012/6/10',null union all
select 'A2','2012/6/11',null union all
select 'A1','2012/6/14',null union all
select 'A1','2012/6/15',null
--------------开始查询--------------------------
select
a.账号,a.日期,
isnull((select sum(收入-支出) from t1 where 账号=a.账号 and 日期<a.日期),0) as 今日余额
from
t1 a join t2 b
on
a.账号=b.账号 and a.日期=b.日期
order by
日期
----------------结果----------------------------
/* 账号 日期 今日余额
---- ----------------------- -----------
A1 2011-06-10 00:00:00.000 0
A2 2012-06-10 00:00:00.000 0
A2 2012-06-11 00:00:00.000 100
A1 2012-06-11 00:00:00.000 200
A1 2012-06-14 00:00:00.000 100
A1 2012-06-15 00:00:00.000 0
(6 行受影响)
*/
------解决方案--------------------
--> 测试数据:[表t1]
if object_id('[表t1]') is not null
drop table [表t1]
create table [表t1](
[账号] varchar(2),
[日期] datetime,
[收入] int,
[支出] int
)
go
insert [表t1]
select 'A1','2011/6/10',200,0 union all
select 'A1','2012/6/11',0,100 union all
select 'A2','2012/6/10',100,0 union all
select 'A2','2012/6/11',100,0 union all
select 'A1','2012/6/14',0,100 union all
select 'A1','2012/6/15',300,0
go
select
[账号],
[日期],
[收入],
[支出],
(select SUM(isnull([收入],0)-isnull([支出],0))
from [表t1] b where a.[账号]=b.[账号] and b.日期<=a.日期) as [今日余额],
isnull((select SUM(isnull([收入],0)-isnull([支出],0))
from [表t1] b where a.[账号]=b.[账号] and b.日期<a.日期),0) as [昨日余额]
from
[表t1] a
order by
[账号],[日期]
/*
账号 日期 收入 支出 今日余额 昨日余额
---------------------
A1 2011-06-10 00:00:00.000 200 0 200 0
A1 2012-06-11 00:00:00.000 0 100 100 200
A1 2012-06-14 00:00:00.000 0 100 0 100
A1 2012-06-15 00:00:00.000 300 0 300 0
A2 2012-06-10 00:00:00.000 100 0 100 0
A2 2012-06-11 00:00:00.000 100 0 200 100
*/