如果已分配项目,则TSQL检索下一个项目

问题描述 投票:2回答:1

我有一个样本数据集,看起来像:

enter image description here

如果尚未获取该值,我需要返回下一个值。

我想通过不使用游标来实现。应返回的数据以黄色突出显示。

有什么想法吗?

谢谢

sql tsql greatest-n-per-group recursive-query
1个回答
0
投票

这是使用递归cte和窗口函数的一种方法:

with 
    tab as (
        select 
            t.*, 
            dense_rank() over(order by item) drn
        from mytable t
    ),
    cte as (
        select t.* from tab t where drn = 1
        union all
        select t.*
        from tab t
        inner join cte c on t.drn = c.drn + 1 and t.itemb > c.itemb
    )
select select item, itemb, date
from cte c
where itemb = (select min(itemb) from cte c1 where c1.item = c.item)

派生表tab根据item为每个记录分配等级(具有相同item的记录获得相同的等级)。

然后,递归cte从对应于第一个item的行开始,并逐个处理item,确保“下一个” itemb大于前一个。

最后,外部查询在每个itemb的第一个item上进行过滤。

Demo on DB Fiddle

项目| itemb |日期:- :---- | :---------X | A | 2014-01-01Y | B | 2014-01-02Z | C | 2014-01-02
© www.soinside.com 2019 - 2024. All rights reserved.