;with cte1 as
( select id,
row_number() over (partition by pk,pp,sn order by id asc)
as rn
from mqms_production
) select * into #M from cte1 where rn=1
通过上面的描述,我获得了rn = 1的所有行,但我还想将给定分区pk,pp,sn的所有行复制到另一个表中。
是否可以在不必再次编写cte块的情况下执行此操作 (由id DESC按pk,pp,sn顺序划分)
谢谢!
答案 0 :(得分:2)
您可以使用反向排序顺序添加另一个基于窗口函数的表达式,并在它们两者上获得顶行
with cte1 as (
select id,
row_number() over (partition by pk,pp,sn order by id asc) as rn1,
row_number() over (partition by pk,pp,sn order by id desc) as rn2
from mqms_production
)
select * from cte1
where rn1 = 1 or rn2 = 1;