SQL 带过滤器的最大和最小日期
SQL max and min dates with filter
以下帐户于 2018 年 1 月 19 日关闭,然后于 2018 年 2 月 27 日重新打开,然后于 2018 年 3 月 26 日再次关闭。如何编写 sql 以捕获此帐户的打开和关闭时间。 closerestrictind = 'C' 是帐户关闭的时间。
我们在数据仓库中工作,每天加载数据以捕获所有历史记录。
帐户 1234 应如下所示:
closed on 1/19/2018
re-opened on 2/27/2018
closed on 3/26/2018
谢谢!
您可以使用 lag()
:
select acctnbr, effectivedate,
(case when closerestrictedind = 'C' then 'closed' else 'opened' end) as action
from (select t.*, lag(closerestrictedind) over (partition by acctnbr order by effectivedate) as prev_cr
from t
) t
where prev_cr <> closerestrictedind;
您可以执行两个 select 语句,第一个 row_number() 按 acctnbr 分区,按日期排序...将其保存在 tmp table
第二个 select,将此 table 与其自身、t1 和 t2 进行内部连接。
其中 t1.closerestrictedind = 'C'
以及 t1.rownum > t2.rownum +1
的连接
以下帐户于 2018 年 1 月 19 日关闭,然后于 2018 年 2 月 27 日重新打开,然后于 2018 年 3 月 26 日再次关闭。如何编写 sql 以捕获此帐户的打开和关闭时间。 closerestrictind = 'C' 是帐户关闭的时间。
我们在数据仓库中工作,每天加载数据以捕获所有历史记录。
帐户 1234 应如下所示:
closed on 1/19/2018
re-opened on 2/27/2018
closed on 3/26/2018
谢谢!
您可以使用 lag()
:
select acctnbr, effectivedate,
(case when closerestrictedind = 'C' then 'closed' else 'opened' end) as action
from (select t.*, lag(closerestrictedind) over (partition by acctnbr order by effectivedate) as prev_cr
from t
) t
where prev_cr <> closerestrictedind;
您可以执行两个 select 语句,第一个 row_number() 按 acctnbr 分区,按日期排序...将其保存在 tmp table
第二个 select,将此 table 与其自身、t1 和 t2 进行内部连接。
其中 t1.closerestrictedind = 'C'
以及 t1.rownum > t2.rownum +1
的连接