我有一个表,其中包含诸如Price_Date,分类,大小,等级,国家和价格等列。该表有时不包含星期日或节假日的数据(例如圣诞节,感恩节等)。
我要在这里实现的是,当表中不包含特定日期的数据时,我希望它自动填充前一天的数据。
例如,该表不包含01/06/2019数据。它根本没有日期。在这种情况下,我想自动分配丢失的01/06/2019日期并用01/05/2019数据填充它。
Price_Date Catagory Size Grade Country Price
--------------------------------------------------------------------------------
2019-01-05 0 32 1 2 24.25
2019-01-05 0 36 1 2 24.25
2019-01-05 0 40 1 2 24.25
2019-01-05 0 48 1 2 24.25
2019-01-05 0 60 1 2 23.25
2019-01-05 0 70 1 2 21.25
2019-01-05 0 84 1 2 17.25
这是我想到的SQL查询。
对不起,如果我在错误的部分发布了这篇文章。
WITH MyRowSet
AS
(
select distinct
d.date_key
,p.Size_Value
,Catagory_Value
,cast (Price_Date as datetime) as prev_effex
,ROW_NUMBER() OVER (PARTITION BY date_key,Size_Value,Catagory_Value order by date_key,cast (Price_Date as datetime) desc) AS RowNum
from
FSPPRICE P
CROSS APPLY Dim_Time d
where
d.Date_KEY <(GETDATE()) and
(D.Date_KEY > (select min(cast (Price_Date as datetime)) as min_date from FSPPRICE))
and
cast (Price_Date as datetime) <> D.Date_Key and cast (Price_Date as datetime) < D.Date_Key
group by d.date_key,Price_Date,Size_Value,Catagory_Value
)
SELECT
r.Date_KEY AS effectiveon
,P.Catagory_Value
,cast(P.Size_Value as varchar) as Size_Value
,P.Grade_Value
,P.Country
,P.Price
,P.Active_Code
FROM MyRowSet AS R INNER JOIN
FSPPRICE AS P
ON r.prev_effex = P.Price_Date and r.Catagory_Value=p.Catagory_Value and r.Size_Value=p.Size_Value WHERE (rownum < 2)
答案 0 :(得分:0)
declare @dt date = GETDATE();--any given date
select @dt as price_date, category, size, grade, grade, country, price
from
@t
where price_date in (select MAX(price_date) price_date from @t where price_date <= @dt)