日期:2014-05-16  浏览次数:20499 次

如何填补稀疏数据中的空隙?
数据通常以稀疏形式进行存储。也就是说,如果在某一给定时间没有任何值存在,则在事实表中没有行存在。如下表(datadate、codeType、ccy是主键):
Datadate codeType ccy rate
20110101 50001 001 0.11
20110109 50001 001 0.12
20110112 50001 001 0.112
20110131 50001 001 0.121
20110101 50002 012 1.61
20110106 50002 012 1.62
20110207 50002 012 1.612
20110308 50002 012 1.63

如果1.2日到1.8日的汇率没有变化,则不存储。请问如何填补中间的空隙?

------解决方案--------------------
--> 测试数据: [ta]
if object_id('[ta]') is not null drop table [ta]
 go
 create table [ta] ([Datadate] datetime,[codeType] int,[ccy] varchar(3),[rate] numeric(4,3))
insert into [ta]
select '20110101',50001,'001',0.11 union all
select '20110109',50001,'001',0.12 union all
select '20110112',50001,'001',0.112 


select * from [ta]

;with
wang as(
select replace(convert(varchar(10),dateadd(day,a.number,'2011-01-01'),120),'-','')  as Datadate,
b.codeType,b.ccy,b.rate
from master..spt_values a
left join ta b on replace(convert(varchar(10),dateadd(day,a.number,'2011-01-01'),120),'-','')=b.Datadate
where type='P' and number<30)

select datadate
  ,codetype=ISNULL(codetype,(select top 1 codetype from wang where datadate<t.datadate  and codetype is not null order by Datadate desc))
  ,ccy=ISNULL(ccy,(select top 1 ccy from wang where datadate<t.datadate and codetype is not null order by Datadate desc))
  ,rate=ISNULL(rate,(select top 1 rate from wang where datadate<t.datadate  and codetype is not null order by Datadate desc))
from wang t

20110101 50001 001 0.110
20110102 50001 001 0.110
20110103 50001 001 0.110
20110104 50001 001 0.110
20110105 50001 001 0.110
20110106 50001 001 0.110
20110107 50001 001 0.110
20110108 50001 001 0.110
20110109 50001 001 0.120
20110110 50001 001 0.120
20110111 50001 001 0.120
20110112 50001 001 0.112
20110113 50001 001 0.112
20110114 50001 001 0.112
20110115 50001 001 0.112
20110116 50001 001 0.112
20110117 50001 001 0.112
20110118 50001 001 0.112
20110119 50001 001 0.112
20110120 50001 001 0.112
20110121 50001 001 0.112
20110122 50001 001 0.112
20110123 50001 001 0.112
20110124 50001 001 0.112
20110125 50001 001 0.112
20110126 50001 001 0.112
20110127 50001 001 0.112
20110128 50001 001 0.112
20110129 50001 001 0.112
20110130 50001 001 0.112