我的表中有一个下面的数据,我需要得到下面的输出。
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中实现这一点?
发布于 2020-08-03 08:21:50
您可以使用以下递归查询:
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值标识),同时跟踪第一个date和id。然后,外部查询对每棵树的最后一条记录进行筛选。
https://stackoverflow.com/questions/63225544
复制相似问题