[英]Add column as int count based on the occurrence of three other columns. How to use ROW_NUMBER with insert?
I need an additional column which counts the unique occurrences of the combination of three other columns.我需要一个额外的列来计算其他三列组合的唯一出现次数。 I'm able to do this with ROW_NUMBER but want to update the table to store the values.
我可以使用 ROW_NUMBER 执行此操作,但想要更新表以存储值。
This works to see it:这可以看到它:
SELECT
ROW_NUMBER() OVER (PARTITION BY EntryDate, DocNo, Item ORDER BY EntryUID) AS x,
*
FROM
SourceTable
This is NOT working to update it:这不能更新它:
WITH TableA AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY EntryDate, DocNo, Item ORDER BY EntryUID) AS x,
*
FROM
SourceTable
)
UPDATE SourceTable
SET SourceTable.NEWCount = TableA.x
WHERE SourceTable.EntryUID = TableA.EntryUID
I get this error message:我收到此错误消息:
Msg 4104, Level 16, State 1, Line 17
消息 4104,级别 16,状态 1,第 17 行
The multi-part identifier "TableA.EntryUID" could not be bound无法绑定多部分标识符“TableA.EntryUID”
Or if you want to use your original approach, you need to include the CTE in the UPDATE
statement - something like this:或者,如果您想使用原始方法,则需要在
UPDATE
语句中包含 CTE - 如下所示:
WITH TableA AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY EntryDate, DocNo, Item ORDER BY EntryUID) AS x,
*
FROM
SourceTable
)
UPDATE src
SET NEWCount = TableA.x
FROM SourceTable src
INNER JOIN TableA ON src.EntryUID = TableA.EntryUID
Assuming that you are running SQL Server, as the error message indicates, you can simply use an updateable CTE:假设您正在运行 SQL Server,如错误消息所示,您可以简单地使用可更新的 CTE:
with cte as (
select newcount,
row_number () over(partition by entrydate, docno, item order by entryuid ) as rn
from sourcetable
)
update cte set newcount = rn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.