我在表中有一个重复的字段, 我想要做的是按顺序计算这个字段,例如下表
ID TEST
1232
1232
1232
1223
1223
1223
1223
我想用以下
更新提交的“TEST”ID TEST
1232 1
1232 2
1232 3
1232 4
1224 1
1224 2
1224 3
我一直在研究下面这段代码,但它没有挑选出所有重复的内容,它只是将大部分内容都设为1。 当我将代码作为选择运行时,它似乎工作得很好,就在我运行更新部分时。任何想法都会非常有用!!
with CTE as (
SELECT ROW_NUMBER() OVER(PARTITION BY [ID] ORDER BY ([ID] ) ) AS Row#,
[ID]
FROM [TABLE]
WHERE [FIELD2 is not null and FIELD3 is not null
)
update [TABLE]
set [TEST]= Row#
from CTE
WHERE [TABLE].FIELD2 is not null
and [TABLE].FIELD3 is not null
and CTE.ROW# = [TABLE].[ID];
答案 0 :(得分:1)
您可以直接更新CTE:
with toupdate as (
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) seqnum
t.*
FROM [TABLE] t
WHERE FIELD2 is not null and FIELD3 is not null
)
update toupdate
set TEST = seqnum
from CTE;
可更新的CTE是SQL Server的一个非常好的功能。
我实际上更喜欢分区子句中的ORDER BY (SELECT NULL)
,因为这强调了排序并不重要。
答案 1 :(得分:0)
您需要YourTable
上的主键(PK)字段,以便知道哪一行分配Row#
值。
with CTE as (
SELECT ROW_NUMBER() OVER(PARTITION BY [ID] ORDER BY [ID] ) AS Row#,
[ID],
[table_pk]
FROM [TABLE]
WHERE [FIELD2 is not null and FIELD3 is not null
)
UPDATE [TABLE]
SET [TEST]= Row#
FROM CTE
WHERE [TABLE].[table_pk] = [CTE].[table_pk];
请注意,您不需要再次包含WHERE
条件,因为您只加入了您在cte上找到的条件。