Sql server 为相同的序列元素分配连续的重复次数

Sql server 为相同的序列元素分配连续的重复次数,sql-server,row-number,Sql Server,Row Number,我使用的SQL Server表如下所示: 差异 笔名 记录数 -7 abc 9 -6 abc 9 -5 abc 7. -4 abc 6. -3 abc 6. -2 abc 6. -1 abc 13 -7 爱好 7. -6 爱好 9 -5 爱好 9 -4 爱好 13 -3 爱好 7. -2 爱好 7. -1 爱好 7. 您只需使用分组方式 with x as ( select nom, rec_num, Count(*) n from t group by nom,rec_

我使用的SQL Server表如下所示:

差异 笔名 记录数 -7 abc 9 -6 abc 9 -5 abc 7. -4 abc 6. -3 abc 6. -2 abc 6. -1 abc 13 -7 爱好 7. -6 爱好 9 -5 爱好 9 -4 爱好 13 -3 爱好 7. -2 爱好 7. -1 爱好 7.
您只需使用
分组方式

with x as (
    select nom, rec_num, Count(*) n
    from t
    group by nom,rec_num
)
update t set t.con_repeats=x.n
from x
join t on t.nom=x.nom and t.rec_num=x.rec_num

编辑

澄清问题后,需要另一种解决方案,它使用
窗口函数
识别重复值的孤岛,并
可更新的CTE
将每个孤岛组的
最大计数
应用于源表:

with groups as (
    select t.*,
        Dense_Rank() over (partition by nom order by (rn - rn2), rec_num) as grp,
        Row_Number() over (partition by nom, (rn - rn2), rec_num order by diff) as c
    from(
        select t.*, row_number() over (partition by nom order by diff) as rn, Row_Number() over (partition by nom, rec_num order by diff) as rn2
        from t
    )t
),
cnt as (
    select *, Max(c) over (partition by nom,grp) maxc
    from groups
)
update cnt set con_repeats=maxc;

select * from t;

看到这个

你能分享你当前的查询吗?你能告诉我代码的性能是什么吗?它会比
行数
组合运行得更快吗?使用num和rec_num上的索引,它会运行得更快-除此之外,您的行数不起作用,因此它是非初学者?!看见您的代码工作不正常,有一个错误与
nom='fav'
diff=-1,-2,-3和-7
@tsr在小提琴没有错误,代码运行。这些值看起来也是正确的,至少在我理解您期望的输出的情况下是这样的——您大概是说该值是错误的吧?“fav”的第1行的值为4,与其他3行相同,有4个“7”;这怎么会错呢?我的意思是,如果有一个序列,例如
55435551
,那么工作的结果应该是
234314341
。我需要的是一行中重复的次数,而不是重复的总数。
nom='fav'
diff=-1、-2、-3和-7出现错误
-- Please see if this helps.

SELECT t1.*, repeats FROM tbl t1
INNER JOIN 
    (SELECT repeats, nom, rec_num FROM (
        (SELECT COUNT(*) repeats, nom, rec_num FROM tbl GROUP BY nom, rec_num))t
     ) t2
ON t2.nom = t1.nom and t2.rec_num = t1.rec_num
ORDER BY nom, diff DESC