请教各位大大
我有一张这样的表格
if object_id('tempdb.dbo.#TA') is not null drop table #TA
go
create table #TA([DWeek] varchar(10),[Itemid] VARCHAR(20),[Qty] int)
insert #TA select 'W201420','A001',5
union all select 'W201421','A001',1
union all select 'W201422','A001',2
union all select 'W201426','A001',3
union all select 'W201427','A001',4
union all select 'W201430','A001',5
union all select 'W201421','A002',100
union all select 'W201429','A002',6
union all select 'W201430','A002',7
union all select 'W201431','A002',8
union all select 'W201432','A002',9
union all select 'W201433','A002',10
union all select 'W201437','A003',11
我想得到数据:
取得原始数据(上表)中最早的一周(DLWEEK这一列),及最晚的一周,然后按顺序显示出来,如果之前数据,则补上这条记录,但显示为0,如下表。
DWeek Itemid qty
w201420 A01 5
w201421 A01 1
w201422 A01 2
w201423 A01 0
w201424 A01 0
w201425 A01 0
w201426 A01 3
w201427 A01 4
w201428 A01 0
w201429 A01 0
w201430 A01 5
w201431 A01 0
w201432 A01 0
w201433 A01 0
w201434 A01 0
w201420 A02 0
w201421 A02 100
w201422 A02 0
w201423 A02 0
w201424 A02 0
w201425 A02 0
w201426 A02 0
w201427 A02 0
w201428 A02 0
w201429 A02 6
w201430 A02 7
w201431 A02 8
w201432 A02 9
w201433 A02 10
w201434 A02 0
------解决方案--------------------
我自己把这类问题叫做“断点补全”,每个问题都有自己的特点,有不少类似的问题,
但是这类问题归根结底就是连续数据中间有“断点”
这里只提供个思路,就是先按照原始规律生成一张包含连续数据的表,然后再外连接
楼主可以参考这个,论坛上很多类似的问题
http://bbs.csdn.net/topics/390781130
------解决方案--------------------
create table #TA([DWeek] varchar(10),[Itemid] VARCHAR(10),[Qty] int)
insert #TA
select 'W201420','A001',5
union all select 'W201421','A001',1
union all select 'W201422','A001',2
union all select 'W201426','A001',3
union all select 'W201427','A001',4
union all select 'W201430','A001',5
union all select 'W201421','A002',100
union all select 'W201429','A002',6
union all select 'W201430','A002',7
union all select 'W201431','A002',8
union all select 'W201432','A002',9
union all select 'W201433','A002',10
union all select 'W201437','A003',11
select a.DWeek,b.Itemid,isnull(c.Qty,0) 'Qty'
from
(select 'W2014'+rtrim(number) 'DWeek'
from master.dbo.spt_values
where type='P'
and number between (select min(right(DWeek,2)) from #TA)
and (select max(right(DWeek,2)) from #TA)) a
cross join (select distinct Itemid from #TA) b
left join #TA c on a.DWeek=c.DWeek and b.Itemid=c.Itemid
order by b.Itemid,a.DWeek
/*
DWeek Itemid Qty
----------------- ---------- -----------
W201420 A001 5
W201421 A001 1
W201422 A001 2
W201423 A001 0
W201424 A001 0
W201425 A001 0
W201426 A001 3