country_id store_id item_id wh_id date fg
23 9,478 1,007,047 9,074 3/5/2018 0
23 9,478 1,007,047 9,074 3/7/2018 0
23 9,478 1,007,047 9,074 3/10/2018 0
23 9,478 1,007,047 9,074 3/11/2018 1
23 9,478 1,007,047 9,074 3/17/2018 0
23 9,478 1,007,047 9,074 3/18/2018 1
23 9,478 1,007,047 9,074 3/27/2018 0
23 9,478 1,007,047 9,074 3/28/2018 0
23 9,478 1,007,047 9,074 3/29/2018 0
这是源数据,目标计算规则是
当fg=1
并且在过去56天内至少有1条fg=0
记录(源中没有所有日期)时,它将设置为1,否则为0。
我尝试使用OLAP函数来执行此操作,但是OLAP函数可以按行工作,并且我需要明智地使用数据日期。
答案 0 :(得分:0)
您似乎想要这样的东西:
select (case when fg = 1 and
max(case when fg = 0 then date end) over
(partition by country_id, store_id, item_id, wh_id
order by date
rows between unbounded preceding and current row
) >= date + interval '-56' day
then 1 else 0
end) as target
我正在猜测分区列是什么。逻辑很简单。 。 。用fg = 0
计算最近的日期,并将其用于比较。
答案 1 :(得分:0)
这应该返回您想要的内容:
SELECT tab.*
,CASE WHEN fg = 1
-- latest row with "fg = 0"
AND Last_Value(CASE WHEN fg = 0 THEN datecol END IGNORE NULLS)
Over (PARTITION BY store_id -- or whatever you need
ORDER BY datecol) > datecol-56 -- maybe ">= datecol-56"
THEN 1
ELSE 0
END
FROM tab