当它更改为下一行中的其他标志时,获取同一标志的唯一行号?
Get the unique row number for the same flag when it changes to other flag in the next row?
我是T-SQL
的新手。
谁能帮我搞定这个?
我有以下数据:
Id flg rnum
--------------
11 n 1
11 n 2
11 y 3
11 n 4
11 n 5
11 y 6
11 n 7
当同一个标志在下一行变为其他标志时,我想获得唯一的行号。
想要的结果:
Id flg rnum ranks
-------------------
11 n 1 1
11 n 2 1
11 y 3 2
11 n 4 3
11 n 5 3
11 y 6 4
11 n 7 5
感谢您的帮助。
您可以将 LAG() OVER ([ PARTITION BY .. ] ORDER BY...)
window 解析函数与另一个解析函数一起使用 SUM() OVER ([ PARTITION BY .. ] ORDER BY...)
:
WITH T2 AS
(
SELECT *, LAG(flg,1) OVER ( ORDER BY rnum ) as lg
FROM T --> your original table
)
SELECT id, flg, rnum,
SUM(CASE WHEN flg=lg THEN 0 ELSE 1 END) OVER ( ORDER BY rnum ) AS ranks
FROM T2
create table #temp(id int,flag char(1),rnum int)
insert into #temp values (11,'n',1),(11,'n',2)
,(11,'y',3),(11,'n',4)
,(11,'n',5),(11,'y',6)
,(11,'n',7)
;With CTE as
(
select t.*
,isnull(tt.rnum,t.rnum)NewRnum
from #temp t
outer apply(select top 1 rnum from #temp tt
where t.id=tt.id and t.flag=tt.flag and t.rnum=tt.rnum+1
order by rnum)tt
)
select *
,dense_rank()over(order by newRNum)
from CTE
drop table #temp
我是T-SQL
的新手。
谁能帮我搞定这个?
我有以下数据:
Id flg rnum
--------------
11 n 1
11 n 2
11 y 3
11 n 4
11 n 5
11 y 6
11 n 7
当同一个标志在下一行变为其他标志时,我想获得唯一的行号。
想要的结果:
Id flg rnum ranks
-------------------
11 n 1 1
11 n 2 1
11 y 3 2
11 n 4 3
11 n 5 3
11 y 6 4
11 n 7 5
感谢您的帮助。
您可以将 LAG() OVER ([ PARTITION BY .. ] ORDER BY...)
window 解析函数与另一个解析函数一起使用 SUM() OVER ([ PARTITION BY .. ] ORDER BY...)
:
WITH T2 AS
(
SELECT *, LAG(flg,1) OVER ( ORDER BY rnum ) as lg
FROM T --> your original table
)
SELECT id, flg, rnum,
SUM(CASE WHEN flg=lg THEN 0 ELSE 1 END) OVER ( ORDER BY rnum ) AS ranks
FROM T2
create table #temp(id int,flag char(1),rnum int)
insert into #temp values (11,'n',1),(11,'n',2)
,(11,'y',3),(11,'n',4)
,(11,'n',5),(11,'y',6)
,(11,'n',7)
;With CTE as
(
select t.*
,isnull(tt.rnum,t.rnum)NewRnum
from #temp t
outer apply(select top 1 rnum from #temp tt
where t.id=tt.id and t.flag=tt.flag and t.rnum=tt.rnum+1
order by rnum)tt
)
select *
,dense_rank()over(order by newRNum)
from CTE
drop table #temp