1

私はデータウェアハウスプロジェクトに取り組んでおり、クライアントは毎日の売上データを提供しています。手持ちの数量はほとんどの行で提供されていますが、多くの場合欠落しています。以前のOHおよび販売情報に基づいて、これらの不足している値を埋める方法についてサポートが必要です。

サンプルデータは次のとおりです。

Line#  Store  Item  OnHand  SalesUnits  DateKey
-----------------------------------------------
1      001    A     100     20          1       
2      001    A     80      10          2       
3      001    A     null    30          3       --[OH updated with 70 (80-10)]
4      001    A     null    5           4       --[OH updated with 40 (70-30)]
5      001    A     150     10          5       --[OH untouched]
6      001    B     null    4           1       --[OH untouched - new item]
7      001    B     80      12          2       
8      001    B     null    10          3       --[OH updated with 68 (80-12]

OnHandの数量が存在するため、1行目と2行目は更新されません。
3行目と4行目は、前の行に基づいて更新されます。
OnHandが提供されているため、5行目はそのままにしておきます。
6行目はアイテムBの最初の行であるため、そのままにしておきます。

集合演算でこれを行う方法はありますか?fast_forwardカーソルを使用して簡単に実行できることはわかっていますが、時間がかかります(15M以上の行)。

ご協力いただきありがとうございます!

4

1 に答える 1

0

テストデータ:

declare @t table(
Line# int,  Store char(3),  Item char,  OnHand int,  SalesUnits int, DateKey int
)

insert @t values
(1,  '001',  'A',  100,   20, 1),
(2,  '001',  'A',  80 ,   10, 2),
(3,  '001',  'A',  null,  30, 3),
(4,  '001',  'A',  null,   5, 4),
(5,  '001',  'A',  150,   10, 5),
(6,  '001',  'B',  null,   4, 1),
(7,  '001',  'B',  null,   4, 2),
(8,  '001',  'B',  80,    12, 3),
(9,  '001',  'B',  null,  10, 4)

カーソルを使用せずにデータを入力するスクリプト:

;with a as
(
select Line#,  Store,  Item,  OnHand,  SalesUnits, DateKey, 1 correctdata from @t where DateKey = 1
union all
select t.Line#,  t.Store,  t.Item,  coalesce(t.OnHand, a.onhand - a.salesunits),  t.SalesUnits, t.DateKey, t.OnHand from @t t
join a on a.DateKey = t.datekey - 1 and a.item = t.item and a.store = t.store
)
update t
set OnHand = a.onhand 
from @t t join a on a.line# = t.line#
where a.correctdata is null

カーソルを使用してデータを入力するスクリプト:

declare @datekey int, @store int, @item char, @Onhand int, 
@calculatedonhand int, @salesunits int, @laststore int, @lastitem char

DECLARE sales_cursor 
CURSOR FOR  
SELECT datekey+1, store, item, OnHand -SalesUnits, salesunits
FROM @t sales  
order by store, item, datekey

OPEN sales_cursor;  
FETCH NEXT FROM sales_cursor  
INTO @datekey, @store, @item, @Onhand, @salesunits

WHILE @@FETCH_STATUS = 0 
BEGIN  
SELECT @calculatedonhand = case when @laststore = @store and @lastitem = @item 
then coalesce(@onhand, @calculatedonhand - @salesunits) else null end
,@laststore = @store, @lastitem = @item

UPDATE s
SET onhand=@calculatedonhand
FROM @t s
WHERE datekey = @datekey and @store = store and @item = item
and onhand is null and @calculatedonhand is not null

FETCH NEXT FROM sales_cursor  
INTO @datekey, @store, @item, @Onhand, @salesunits

END 
CLOSE sales_cursor; 
DEALLOCATE sales_cursor; 

カーソルバージョンを使用することをお勧めします。再帰クエリを使用して適切なパフォーマンスを得ることができるとは思えません。ここにいる人はカーソルが嫌いなのは知っていますが、テーブルがそのサイズの場合、それが唯一の解決策になる可能性があります。

于 2012-02-23T14:04:01.237 に答える