我正在编写一个窗口函数,应该创建一个月窗口,并且仅在所述月窗口内的更新标志字段中获取具有最大值的记录。
我的窗口函数有问题,当它仅应显示最大值时,它仍在窗口中显示所有结果。
我在下面留下了我的代码。请帮助。
SELECT
gb1.SKU_Id,
gb1.Warehouse_Code,
gb1.Period_Start,
gb1.country,
tm.c445_month,
tm.report_date,
gb1.update_flag,
max(gb1.update_flag) over (partition by tm.yearmonth order by gb1.update_flag range between unbounded preceding and current row ) as update_window,
SUM(gb1.TOTAL_NEW_SALES_FORECAST) AS dc_forecast
FROM BAS_E2E_OUTPUT_GLOBAL_FCST gb1
inner join (
SELECT
gb2.SKU_Id,
gb2.Warehouse_Code,
gb2.Period_Start,
gb2.country,
gb2.update_flag,
gb2.report_date,
tm1.week_date,
tm1.c445_month,
tm1.yearmonth
FROM BAS_E2E_OUTPUT_GLOBAL_FCST as gb2
left join (
select distinct(week_date) as week_date,
c445_month,
yearmonth
from "PROD"."INV_PROD"."BAS_445_MONTH_ALIGNMENT"
group by c445_month, week_date, yearmonth
) as tm1 on gb2.report_date = tm1.week_date
group by SKU_Id,
Warehouse_Code,
Period_Start,
country,
update_flag,
report_date,
tm1.week_date,
tm1.c445_month,
tm1.yearmonth
) as tm
on gb1.report_date = tm.week_date
and gb1.SKU_ID = tm.sku_id
and gb1.Warehouse_Code = tm.warehouse_code
and gb1.Period_Start = tm.period_start
and gb1.country = tm.country
GROUP BY
gb1.SKU_Id,
gb1.Warehouse_Code,
gb1.Period_Start,
gb1.country,
tm.c445_month,
tm.yearmonth,
tm.report_date,
gb1.update_flag
您当前正在使用MAX
,并且该窗口被定义为上一行,包括当前行。因此,正确地,它返回的最大值可能应该为每个记录更改。也许您想将max超过固定分区:
MAX(gb1.update_flag) OVER (PARTITION BY tm.yearmonth) AS update_window
顺便说一句,如果您did确实打算将MAX
与当前的窗口逻辑一起使用,则在大多数SQL版本中,ORDER BY
子句可以简化为:
MAX(gb1.update_flag) OVER (PARTITION BY tm.yearmonth ORDER BY gb1.update_flag) AS update_window
即,默认范围在当前行之前是无界的,因此不必这么说。