读书人

怎么取得前一天的数据~

发布时间: 2012-02-28 13:06:35 作者: rapoo

如何取得前一天的数据~~~
我指的前一天,是一组数据,不指定日期

日期 产品A 产品B

2007-1-1 20 30
2007-1-2 50 60
2007-1-3 80 100

想得到

日期 今天的A+B 昨天(A+B)
2007-1-1 50 0
2007-1-2 110 50
2007-1-3 180 110

这样的SQL 怎么写,谢谢各位

[解决办法]
Select
日期,
SUM(A.A + A.B) As 今天,
IsNull((Select SUM(B.A + B.B) From TableName Where 日期 < A.日期), 0) As 昨天
From
TableName A
[解决办法]
create table #test(日期 datetime,产品A int ,产品B int)
insert into #test(日期,产品A,产品B)
select '2007-1-1 ', '20 ', '30 ' union
select '2007-1-2 ',50,60 union
select '2007-1-3 ',80,100


select 日期,isnull((select 产品A + 产品B from #test where #test.日期=t.日期),0) as '今天的A+B ',
isnull((select 产品A + 产品B from #test where datediff(dd,#test.日期,t.日期)= 1),0) as '昨天的A+B '
from #test t

drop table #test

读书人网 >SQL Server

热点推荐