创建一个标志以了解列是否处于多个间隔中



我在SQL中很难创建基于间隔的标志。

这是我的用例:

表:结果

start_month12m_before>end_month202109202010202010202010202009202001
commercessing_month client_idend_month112m_beforestart_month
202106 客户端1 201910 20209 202010
202006 客户端1 201910 202009202109
202003 客户端2 201910 202009202109
202012 客户端3 201910 20209202109
202012 客户端4 201910202003202109
202012 客户端4 201910 202009202109

如果您只是想确认这两个条件在同一客户端的至少一行上都成立:

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'的值。

最新更新