我有輸入表,需要添加缺失的日期,但不是最大,而是直到下一個可用月份。所以我需要使用回圈。
SET @mindate = '2021.01'
SET @maxdate = CAST( GETDATE() AS Date ) --date today as max date
while
begin
if @mindate => @maxdate
begin
break
end
set @mindate = @mindate 1
end
然后我可以得到 1 .. 但它不會停止到 7 個月
所以我完全陷入了寫作回圈。
資料表:

有人可以幫忙寫代碼嗎?因為大多數示例都是連接、資料表或一個最大值。
uj5u.com熱心網友回復:
保羅,我假設您忘記在模擬資料中指定月份。
我希望下面的代碼可以幫助您了解您正在嘗試完成的作業是多么重要:-) 感謝您擺脫回圈的意愿。
為了使它更好,我建議進行非規范化(注意!):
- 創建另一列
price_valid_until - 最新的價格記錄將有
price_valid_until = '21000101'(又名,遙遠的未來) - 注冊新價格時,更新以前的價格
new price_valid_from - 1 day
這是解決方案,具有非常復雜但有效的查詢(http://sqlfiddle.com/#!18/4ab23/4)
create table price_history(
SKU varchar(255),
price_valid_from date,
price decimal(16, 2)
)
insert into price_history
values
('a', '20210101', 10),
('a', '20210107', 12),
('b', '20210102', 4),
('b', '20210110', 2),
('b', '20210214', 5);
-- This fiddler won't let me initialize and reference:
--
-- declare
-- @from_date date,
-- @to_date date;
--
-- select
-- @from_date = min(date_from),
-- @to_date = max(date_from)
-- from price_history
with
date_range as(
select
min(price_valid_from) as from_date,
--
eomonth(
max(price_valid_from)
) as to_date
from price_history
),
--
all_dates as(
select from_date as date_in_range
from date_range
-- ----------
union all
-- ----------
select dateadd(day, 1, date_in_range)
from all_dates
where
date_in_range < (
select to_date
from date_range
)
),
--
price_history_boundaries as(
select
ph.SKU,
ph.price,
--
ph.price_valid_from,
-- The latest price, so far, is valid until 01/01/2100
coalesce(
dateadd(
day,
-1,
min(ph_next.price_valid_from)
),
'21000101'
) as price_valid_until
from
price_history ph
left outer join price_history ph_next
on(
ph_next.SKU = ph.SKU
and ph_next.price_valid_from > ph.price_valid_from
)
group by ph.SKU, ph.price_valid_from, ph.price
)
select
phb.SKU,
ad.date_in_range,
phb.price
from
all_dates ad
inner join price_history_boundaries phb
on(
phb.price_valid_from <= ad.date_in_range
and phb.price_valid_until >= ad.date_in_range
)
order by phb.SKU, ad.date_in_range
uj5u.com熱心網友回復:
通過創建要加入的日期串列,您可以輕松實作所需的結果。在這里,我使用遞回 CTE 創建了一系列日期,每次迭代添加 1 個月直到當前日期。
然后是加入源資料的簡單問題,這里lead()可以方便地限制連接的行。此外,假設SQL Server使用Getdate:
declare @start date=(select Min([date]) from sourcetable);
with m as (
select 1 num, @start [Date]
union all
select num 1 , DateAdd(month,1,m.[date])
from m
where DateAdd(month,1,m.[date]) <= GetDate()
), t as (
select *, Lead([date],1,GetDate()) over (order by [date]) NextDate
from sourcetable
)
select m.[Date], t.sku, t.price
from m
join t on m.[date] >= t.[date] and m.[date] < t.nextdate
見作業小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/368640.html
上一篇:協議中關聯型別的依賴倒置
