我正在尝试从现有的稀疏表中填充一个#temp报告表,其中包含2个关键元素-datekeys和基于日期范围和价格的价格变化。这是价格更改表中存在的数据:
2天前(连续7天)滚动报告的日期范围将为6/12-6/19。表中的2行的旧价格和旧价格差异都超出该报告的范围6/7,但是,需要价格和差异才能在CashPrice列下复制所有日期键20190612至20190618的价格。在6/19,有一个新的价格变化/差异。在那 datekey,新的价格/差异值应更改。
报告所需的设置数据如下:
以下是构建采样数据的代码:
-- T-SQL script to build the sampling tables
-- use for date-related cross-join later
if object_id( N'tempdb..#Numbers', N'U' ) is not null
drop table #Numbers;
create table #Numbers(
n int
);
insert #Numbers( n ) values( 0 ), ( 1 ), ( 2 ), ( 3 ), ( 4 ), ( 5 ), ( 6 ),
( 7 ), ( 8 ), ( 9 ), ( 10 )
-- select * from #Numbers;
-- creating existing sparse price data
if object_id( N'tempdb..#dt', N'U' ) is not null
drop table #dt;
create table #dt(
StoreNumber int
, City char( 3 )
, State char( 2 )
, Type char( 1 )
, ProductKey int
, DateKey int
, CashPrice money
, DateLastPriceChange datetime
, CashPriceVar money
)
insert #dt values
( 1, 'OKC', 'OK', 'D', 144, 20190607, 2.799, '2019-06-07 11:37', -0.1 )
, ( 1, 'OKC', 'OK', 'D', 144, 20190619, 2.699, '2019-06-19 10:40', -0.1 )
-- select * from #dt;
-- creaing temporary working table for reporting
if object_id( N'tempdb..#tt', N'U' ) is not null
drop table #tt;
create table #tt(
StoreNumber int
, City char( 3 )
, State char( 2 )
, Type char( 1 )
, ProductKey int
, DateKey int
-- a couple of extra columns here
, DateKeyDate date
, DataDateKey int
, CashPrice money
, DateLastPriceChange datetime
, CashPriceVar money
)
-- dub in the start date for the report
declare @StartDateKey date = '2019-06-12'
-- populate the temporary working table
insert #tt( StoreNumber, ProductKey, DateKeyDate )
select distinct
dt.StoreNumber
, dt.ProductKey
, dateadd( day, n.n, @StartDateKey )
from #dt dt
cross join #Numbers n
where
n.n <= 7
-- select * from #tt
-- change the added datekeydate to datekey format
update #tt
set DateKey = year( DateKeyDate ) * 10000 + month( DateKeyDate ) * 100 +
day( DateKeyDate )
这是我一直在处理的代码。这并不理想,而且在很多情况下,它无法获取整套数据,它会过滤掉我交叉加入的日期,因此我没有估算的数据,只能显示原始的已知价格变化。请告知。
select
dd.StoreNumber
, dto.City
, dto.State
, dto.Type
, dd.ProductKey
, dd.DateKey
, dto.CashPrice
, dto.DateLastPriceChange
, dto.CashPriceVar
from (
select
tt.StoreNumber
, tt.ProductKey
, tt.DateKey
, max( dt.DateKey ) MaxDateKey
from #tt tt
inner join #dt dt
on dt.StoreNumber = tt.StoreNumber
and dt.ProductKey = tt.ProductKey
and dt.DateKey <= tt.DateKey
group by
tt.StoreNumber
, tt.ProductKey
, tt.DateKey
) dd
inner join #dt dto
on dto.StoreNumber = dd.StoreNumber
and dto.ProductKey = dd.ProductKey
and dto.DateKey = dd.MaxDateKey;