我有一个非常复杂的查询,需要帮助。
我有一个包含Order_ID
,Date
和Day
的表。
我需要获取每月Week_No
的星期。此字段有4个关键条件。
001
。Week_No
将始终从001
开始,即使没有其他条目导致该条目的特定Date
。Week_No
始终以1递增,即使一个月的特定星期没有订单。举例说明条件3和4。,
如果6月份的订单只有2个,分别是2020-06-29
和1 2020-06-11
,则Week_No
将是002
和{{1 }},分别用于前者和后者。
希望我的下表足够清楚。
001
答案 0 :(得分:1)
嗯。 。 。您实际上可以利用潜在客户和累计金额来完成此操作。逻辑基本上是:
逻辑如下:
select t.*,
sum(case when extract(year_month from date) <> extract(year_month from prev_date) or prev_date is null
then 1
when datediff(date, prev_date) >= 7
then 1
when day = 'Fri' or
day = 'Thu' and prev_day not in ('Fri') or
day = 'Wed' and prev_day not in ('Fri', 'Thu') or
day = 'Tue' and prev_day not in ('Fri', 'Thu', 'Wed') or
day = 'Mon' and prev_day not in ('Fri', 'Thu', 'Wed', 'Tue') or
day = 'Sun' and prev_day not in ('Fri', 'Thu', 'Wed', 'Tue', 'Mon')
then 0
else 1
end) over (order by date) as week_num
from (select t.*,
lag(date) over (order by date) as prev_date,
lag(day) over (order by day) as prev_day
from t
) t