我们的ERP系统中的一个数据库表只包含这样定价的有效日期:
Partnumber ||Effective Date || Price
----------------------------------------------
abc || 2012-01-01 || $ 1,00
abc || 2012-02-01 || $ 1,10
xyz || 2012-01-01 || $ 1,00
我的尺寸表如下:
Partnumber |Start Date || EndDate || Price
-----------------------------------------------------------------
abc || 2012-01-01 || 2012-01-31 ||$ 1,00
abc || 2012-02-01 || <NULL> ||$ 1,00
xyz || 2012-01-01 || <NULL> ||$ 1,00
这使我能够根据StartDate和EndDate之间的orderdate(或EndDate IS NULL)找到合适的价格
最后我的问题:如果有一个新的EffectiveDate的新记录,我怎么能更新EndDate enddate = new recored startDate-1。
答案 0 :(得分:0)
表中的startdate定义为varchar(20)&amp;结束日期为int。这是一个错误吗?我不确定你希望将结束日期(作为int)设置为,因为它比新的startdate少1。
我的代码可以完成这项工作,包括datetime或smalldatetime数据类型的startdates和enddates。如果你的表实际上是你给出的结构,你将不得不相应地调整逻辑。
这个逻辑应该放在存储过程中。
declare stageCursor cursor scroll for
select name, startdate, enddate from staging;
declare @name varchar(20),
@startdate datetime,
@enddate datetime;
open stageCursor
fetch next from stageCursor into @name, @startdate, @enddate
while @@fetch_status = 0 begin
update operations set o.enddate = dateadd(d, -1, s.startdate)
where name = @name --does this need to be restricted to just the latest operations row somehow?
insert operations (name, startdate, enddate)
values (@name, @startdate, @enddate);
fetch next from stageCursor into @name, @startdate, @enddate
end
close stageCursor
deallocate stageCursor
truncate table staging --I presume after the data has been used to update the
--operations table, it isnt going to wanted anymore
答案 1 :(得分:0)
试试这个:
with t as
(
select
row_number() over (partition by Partnumber order by [Effective Date]) as row_id,
*
from your_table
)
select
t_start.Partnumber,
t_start.[Effective Date] as start_dt,
dateadd(day,-1,t_end.[Effective Date]) as end_dt,
t_start.Price
from
t as t_start
left join
t as t_end
on
t_start.row_id+1 = t_end.row_id and t_start.Partnumber=t_end.Partnumber
<强>更新强>
如果你想更新your_table中的end_date,你可以:
update your_table
set end_dt = (select dateadd(day,-1,min(t.start_dt)) from your_table t
where t.Partnumber=your_table.Partnumber
and t.start_dt>your_table.start_dt);
结果可能会有两个连续期间的重复价格,此处为the approach以解决此问题。
您可以使用此SQL FIDDLE DEMO进行测试。