递归 Cte 在 SQL 中查找 Min 和 Max 相关数据?
Recursive Cte to find Min and Max related data's in SQL?
我的 table 中有以下类型的数据,我需要获得以下类型的输出。
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 中实现这一点?
您可以使用以下递归查询:
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
值标识)开始迭代遍历层次结构,同时跟踪第一个 date
和 id
。然后,外部查询过滤每棵树的最后一条记录。
我的 table 中有以下类型的数据,我需要获得以下类型的输出。
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 中实现这一点?
您可以使用以下递归查询:
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
值标识)开始迭代遍历层次结构,同时跟踪第一个 date
和 id
。然后,外部查询过滤每棵树的最后一条记录。