您不能完全做到这一点,row_number() over (partition by ... order by ...)
而且CTE
查询似乎也不起作用。我喜欢尽可能避免使用游标,但游标可能适合您的情况:
declare @tbl table (id int, x char(1), y int, z int null)
declare
@id int, @x char(1), @y int,
@x2 char(1) = null, @y2 int = null, @z int
insert into @tbl (id, x, y) values
(1, 'a', 0), (2, 'a', 0), (3, 'a', 0),
(4, 'a', 1),
(5, 'a', 0), (6, 'a', 0),
(7, 'a', 2),
(8, 'a', 3),
(9, 'b', 0),
(10, 'b', 1),
(11, 'b', 0), (12, 'b', 0),
(13, 'b', 2),
(14, 'b', 3),
(15, 'b', 0), (16, 'b', 0)
declare cr cursor for
select id, x, y
from @tbl
order by id
open cr
fetch next from cr into @id, @x, @y
while @@fetch_status = 0
begin
set @z =
case when @x2 is null or @x <> @x2
then 1
else
case when @y = @y2
then @z
else @z + 1
end
end
update @tbl
set z = @z
where id = @id
set @x2 = @x
set @y2 = @y
fetch next from cr into @id, @x, @y
end
close cr
deallocate cr
select x, y, z
from @tbl
order by id