【问题标题】:Simplify sql query(date to period)简化 sql 查询(日期到期间)
【发布时间】:2019-12-28 16:46:25
【问题描述】:

得到这张表: initial table

需要得到这样的表: Target table

我用了什么:

Select ID_CLIENT, BALANCE, HIST_DT as Start_dt, isnull(lead(hist_dt) over (partition by id_client order by hist_dt asc), '2999.12.31') as End_dt
from (
select ID_CLIENT, ID_STATUS, balance, hist_dt, lag(id_status) over (partition by id_client order by id_status) as Prev_ID_status
from Client_History) a
where a.ID_STATUS = a.Prev_ID_status or a.ID_STATUS = 1
order by ID_CLIENT, HIST_DT

我认为它非常复杂。很高兴听到任何简化此查询的建议。

【问题讨论】:

  • 我认为您可以在Balance 更改为id_client 时进行查询

标签: sql date simplify period balance


【解决方案1】:

这是一个间隙和孤岛问题,最容易通过行数和聚合的差异来解决:

select id_client, balance, min(hist_dt), max(hist_dt)
from (select ch.*,
             row_number() over (partition by id_client order by balance_hist_dt) as seqnum,
             row_number() over (partition by id_client, balance order by balance_hist_dt) as seqnum_2
      from client_history ch
     ) ch
group by id_client, balance, (seqnum - seqnum_2)
order by id_client, min(hist_dt);

为什么这行得通有点难以描述。但是如果您查看子查询的结果,您会发现差异如何捕获具有相同余额的相邻行。

【讨论】:

  • 感谢您的回答。阅读有关此问题的一些信息。但不要在查询中得到 balance_hist_dt 中的第一个下划线
  • @Stepnosound 。 . .我不知道您所说的“获取第一个下划线”是什么意思。
  • 有两列:balance和hist_dt。在您的查询中,它们与“_”结合在一起
  • @Stepnosound 。 . .我修改了答案。
猜你喜欢
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多