我在SQL中很难创建基于间隔的标志。
这是我的用例:
表:结果
commercessing_month | client_id | start_month12m_beforeend_month112m_before | start_month | >end_month|
---|---|---|---|---|
202106 | 客户端1 | 201910 | 20209 | 202010 | 202109
202006 | 客户端1 | 201910 | 202009 | 202010202109 |
202003 | 客户端2 | 201910 | 202009 | 202010202109 |
202012 | 客户端3 | 201910 | 20209 | 202010202109 |
202012 | 客户端4 | 201910 | 202009202003 | 202109 |
202012 | 客户端4 | 201910 | 202009 | 202001202109 |
如果您只是想确认这两个条件在同一客户端的至少一行上都成立:
select *,
case when
max(case when merchandising_month between start_month and end_month then 1 end)
over (partition by client_id) = 1 and
max(case when merchandising_month between start_month_12m_before and end_month_12m_before then 1 end)
over (partition by client_id) = 1
then 'yes' else 'no' end as activity
from T
这不会以任何方式区分行。对于同一行,条件可以同时为真,也可以在集合中多次为真。
这样做的方法是用相同的client_id
环视每一行。对于这些条件中的每一个,都使用case
表达式进行测试,当条件通过时,该表达式的求值结果为1。max()
将多个值折叠成单个结果,使得所有行中的最大值等于1将指示至少一行已经通过测试。如果优选的话,可以将值1改变为类似'Passed'
或'True'
的值。