首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归Cte查找SQL中与Min和Max相关的数据?

递归Cte查找SQL中与Min和Max相关的数据?
EN

Stack Overflow用户
提问于 2020-08-03 07:42:15
回答 1查看 630关注 0票数 0

我的表中有一个下面的数据,我需要得到下面的输出。

代码语言:javascript
复制
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列来识别这一点。我需要低于某种输出。

产出:

代码语言:javascript
复制
O1 - aa - 21 - 25 - tot - V4
01 - aaa - 11 - 12 -zyy - VV3

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-03 08:21:50

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

代码语言:javascript
复制
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列中的previous_id值标识),同时跟踪第一个dateid。然后,外部查询对每棵树的最后一条记录进行筛选。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63225544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档