Select IsNull(DateDiff(dd,日期字段,(Select TOP 1 日期字段 From TableName Where 日期字段<A.日期字段 Order By 日期字段 Desc)),0) As 天数, 金额-IsNull((Select TOP 1 金额 From TableName Where 日期字段<A.日期字段 Order By 日期字段 Desc),0) As 金额 From TableName A
--建立測試環境 Create Table TEST (日期字段 Varchar(10), 金额 Int) Insert TEST Select '2005-03-09', 80 Union All Select '2005-03-10', 115 Union All Select '2005-03-13', 125 Union All Select '2005-03-15', 155 GO --測試 Select IsNull(DateDiff(dd,(Select TOP 1 日期字段 From TEST Where 日期字段<A.日期字段 Order By 日期字段 Desc),日期字段),0) As 天数, 金额-IsNull((Select TOP 1 金额 From TEST Where 日期字段<A.日期字段 Order By 日期字段 Desc),0) As 金额 From TEST A --刪除測試環境 Drop Table TEST --結果 /* 天数 金额 0 80 1 35 3 10 2 30 */
create table table1 ( rq datetime, je int )insert into table1 select '2005-03-09', 80 insert into table1 select '2005-03-10', 115 insert into table1 select '2005-03-13', 125 insert into table1 select '2005-03-15', 155select datediff(day,t3.rq2,t3.rq) as 天数,t3.je - t4.je as jec from (select *,rq2 = (select max(rq) from table1 where rq < t1.rq) from table1 t1 )t3,table1 t4 where t3.rq2 = t4.rq--结果 1 35 3 10 2 30
coolingpipe 你好,结果是对的,分就给,但是不是很明白,能否讲解一下 (select *,rq2 = (select max(rq) from table1 where rq < t1.rq) from table1 t1 (select max(rq) from table1 where rq < t1.rq) 这个起到啥作用谢谢
你的更是对了, 完全不是问题,能否讲解一下 , 分数是先来对的多一些,呵呵,给你多一些,不够另加贴, 能否简单说说 (select *,rq2 = (select max(rq) from table1 where rq < t1.rq) from table1 t1可以得到那个结果,谢谢
你執行這個看看就明白了select *,rq2 = (select max(rq) from table1 where rq < t1.rq) from table1 t1就是得到原來的紀錄集,加上一個字段,rq2,該字段的值為比當前紀錄的日期小的日期中最大的日期。
Create Table TEST
(日期字段 Varchar(10),
金额 Int)
Insert TEST Select '2005-03-09', 80
Union All Select '2005-03-10', 115
Union All Select '2005-03-13', 125
Union All Select '2005-03-15', 155
GO
--測試
Select
IsNull(DateDiff(dd,(Select TOP 1 日期字段 From TEST Where 日期字段<A.日期字段 Order By 日期字段 Desc),日期字段),0) As 天数,
金额-IsNull((Select TOP 1 金额 From TEST Where 日期字段<A.日期字段 Order By 日期字段 Desc),0) As 金额
From TEST A
--刪除測試環境
Drop Table TEST
--結果
/*
天数 金额
0 80
1 35
3 10
2 30
*/
create table table1
(
rq datetime,
je int
)insert into table1 select '2005-03-09', 80
insert into table1 select '2005-03-10', 115
insert into table1 select '2005-03-13', 125
insert into table1 select '2005-03-15', 155select datediff(day,t3.rq2,t3.rq) as 天数,t3.je - t4.je as jec from
(select *,rq2 = (select max(rq) from table1 where rq < t1.rq)
from table1 t1
)t3,table1 t4
where t3.rq2 = t4.rq--结果
1 35
3 10
2 30
from table1 t1 (select max(rq) from table1 where rq < t1.rq) 这个起到啥作用谢谢
from table1 t1可以得到那个结果,谢谢
from table1 t1就是得到原來的紀錄集,加上一個字段,rq2,該字段的值為比當前紀錄的日期小的日期中最大的日期。