当T-SQL中列的值更改时,我可以以某种方式将新组分配给行吗?
如果您能提供无需CTE和功能即可无限制重复号码的解决方案,我将不胜感激。我提出了一种解决方案,该解决方案适用于连续100个相同的数字(使用
coalesce(lag()over(), lag() over(), lag() over() ) - it is too bulky
但无法解决连续无限个相同数字的情况。
数据
id somevalue
1 0
2 1
3 1
4 0
5 0
6 1
7 1
8 1
9 0
10 0
11 1
12 0
13 1
14 1
15 0
16 0
预期
id somevalue group
1 0 1
2 1 2
3 1 2
4 0 3
5 0 3
6 1 4
7 1 4
8 1 4
9 0 5
10 0 5
11 1 6
12 0 7
13 1 8
14 1 8
15 0 9
16 0 9
答案 0 :(得分:1)
如果只需要组标识符,则可以使用:
select t.*,
min(id) over (partition by some_value, seqnum - seqnum_1) as grp
from (select t.*,
row_number() over (order by id) as seqnum,
row_number() over (partition by somevalue order by id) as sequm_1
from t
) t;
如果要枚举。 。 。好了,您可以使用dense_rank()
枚举上面的ID。或者,您可以使用lag()
和累计金额:
select t.*,
sum(case when some_value = prev_sv then 0 else 1 end) over (order by id) as grp
from (select t.*,
lag(somevalue) over (order by id) as prev_sv
from t
) t;
答案 1 :(得分:0)
这是另一种方法:
首先,我创建了一个视图以在每行上提供组增量:
malloc
然后我使用此视图生成组值,作为增量的累积和:
create view increments as
select
n2.id,n2.somevalue,
case when n1.somevalue=n2.somevalue then 0 else 1 end as increment
from
(select 0 as id,1 as somevalue union all select * from mytable) n1
join mytable n2
on n2.id = n1.id+1