Search code examples
sqlsql-updaterow-number

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.

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
The multi-part identifier "TableA.EntryUID" could not be bound


Solution

  • Or if you want to use your original approach, you need to include the CTE in the UPDATE statement - something like this:

    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