私は私が正しくあなたを理解しますが、あなたのテーブルに「ギャップ」を埋めるためにならば、あなたがする必要があるかわかりません毎月の最後の日を挿入します。ここにあなたのためにそれを行うスクリプトがあります。私はSQLでかなり新しいので、これは最善の解決策ではないかもしれませんが、私のために働いた。
declare @dateVar date = '2017-01-01' -- script will start calculating last day of the month from this date. DON'T modify the day value
declare @yearVar int = '2017' -- script insert months until the end of the year in this variable
declare @endDates table
(
item nvarchar(1),
endOfMonthDate date
)
while datepart(year, @dateVar) = @yearVar
begin
insert into @endDates
(item, endOfMonthDate)
values (
'A',
dateadd(day, -1, dateadd(month, 1, @dateVar))
)
set @dateVar = dateadd(month, 1, @dateVar)
end
insert into dbo.table1
(Item, validDate)
(
select item, endOfMonthDate
from @endDates
where endOfMonthDate not in (
select validDate
from table1)
)
今、正しい価格でレコードを更新することは少しトリッキーになります:それはすでにあなたのvalidDate列に存在した日付とない挿入レコードということではないしてください。まず、月の初めからの価格に基づいて、各月末の価格を設定します。
update dbo.table1
set table1.Price = t2.Price
from table1
left join table1 as t2
on month(table1.validDate) = MONTH(t2.validDate)
そして、私たちは前の数ヶ月からの値を使用して価格を持っていない残りのレコードを更新:
declare @loopVar int = 0
declare @nullsNumb int = (select sum(case when table1.Price is null then 1 else 0 end) from table1) --calculates number of nulls in the Price column
while @loopVar < @nullsNumb --not so great solution that inserts previous month's price to every record that doesn't have any price at this moment
begin
update dbo.table1
set table1.Price = t2.Price
from table1
left join table1 as t2
on month(table1.validDate) = MONTH(t2.validDate) + 1
where table1.Price is null
set @loopVar = @loopVar + 1
end
はここvalidDateで注文する場合TABLE1のデータは、今どのように見えるかです:
Item validDate Price
A 2017-01-01 100
A 2017-01-31 100
A 2017-02-28 100
A 2017-03-31 100
A 2017-04-01 120
A 2017-04-30 120
A 2017-05-31 120
A 2017-06-30 120
A 2017-07-31 120
A 2017-08-31 120
A 2017-09-30 120
A 2017-10-31 120
A 2017-11-30 120
A 2017-12-31 120
私が助けられたかどうか教えてください。
カレンダーテーブルを使用する必要があります。これは、毎日(またはあなたのケースでは月末ごとに)行を持つテーブルです。次に、あなたはこのテーブルへの外部結合 –