【问题标题】:Recursive Cte to find Min and Max related data's in SQL? [closed]递归 Cte 在 SQL 中查找 Min 和 Max 相关数据? [关闭]
【发布时间】:2020-11-23 06:58:02
【问题描述】:

我的表中有以下类型的数据,我需要获得以下类型的输出。

U.Id  Current_Id  Previous_Id Date reason values
01        aa          null     21   xyz    V1
01        bb           aa      24   yxz    V2
01        cc           bb      24   out    V3
01        dd           cc      25   tot    V4
01        aaa         null     11   yyz    VV4
01        bbb         aaa      12   zyy    VV3

前四条记录为一组,后两条记录为一组。我们可以通过 current_id 和 Previous_ID 列来识别它。我需要以下类型的输出。

输出:

O1 - aa - 21 - 25 - tot - V4
01 - aaa - 11 - 12 -zyy - VV3

对于每组我需要第一个记录日期和最后一个记录日期、值、原因。我如何在 ms sql 中实现这一点?

【问题讨论】:

    标签: sql tsql sql-server-2012 greatest-n-per-group recursive-query


    【解决方案1】:

    您可以使用以下递归查询:

    with cte as (
        select uid, current_id, previous_id, date, value, date first_date, current_id first_id, 1 lvl
        from mytable 
        where previous_id is null
        union all
        select t.uid, t.current_id, t.previous_id, t.date, c.first_date, c.first_id, c.lvl + 1
        from cte c
        inner join mytable t on t.previous_id = c.current_id and t.uid = c.uid
    )
    select uid, first_id, first_date, date last_date, reason last_reason, value last_value
    from cte c
    where c.lvl = (select max(c1.lvl) from cte c1 where c1.first_id = c.first_id and c1.uid = c.uid)
    

    递归查询从根注释开始迭代地遍历层次结构(由列previous_id 中的null 值标识),同时跟踪第一个dateid。然后,外部查询过滤每棵树的最后一条记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 2011-04-22
      相关资源
      最近更新 更多