日期:2014-05-18  浏览次数:20552 次

存储过程循环查询
日期 | 实际金额 | 理论金额
---------------------------
 29 | 80 | 40
 30 | 70 |  
 31 | | (70)
 01 | | (70)
 02 | | (70)
 03 | 120 | (70)
 04 | 90 | (120)
 05 | 85 | (90)


select distinct 
年月日
,检品日
,点货日
,组CD
,部门CD
,供货商CD
,实际金额
,理论金额= case when 实际金额 <>0 
then (
select 实际金额  
from dbo.viewStockPurchase_Data b 
where b.点货日=(select max(c.点货日) 
from dbo.viewStockPurchase_Data c 
where b.点货日<c.点货日 
)

end 
from dbo.viewStockPurchase_Data as a
where 年月日>'2007/05/01'
group by .....

----------------------------
就是按日期
查询 前一天的实际金额的数据 来填充今天的理论金额
前一天没有就向前推 查询在前一天的数据...直到有数据为止!
(临时表,打印用)
望高手赐教!

------解决方案--------------------
create table #t(日期 datetime,实际金额 int)

insert into #t
select '2007-10-29',80
union select '2007-10-30',70
union select '2007-10-31',null
union select '2007-11-01',null
union select '2007-11-02',null
union select '2007-11-03',120
union select '2007-11-04',90
union select '2007-11-05',85

select 日期,
实际金额,
理论金额 = (select 实际金额 from #t b where b.日期=(select max(日期) from #t where #t.日期<a.日期 and #t.实际金额>0))
from #t a
/*
日期 实际金额 理论金额
------------------------------------------------------ ----------- ----------- 
2007-10-29 00:00:00.000 80 NULL
2007-10-30 00:00:00.000 70 80
2007-10-31 00:00:00.000 NULL 70
2007-11-01 00:00:00.000 NULL 70
2007-11-02 00:00:00.000 NULL 70
2007-11-03 00:00:00.000 120 70
2007-11-04 00:00:00.000 90 120
2007-11-05 00:00:00.000 85 90

(所影响的行数为 8 行)
*/