Search code examples
sql-serversql-server-2017

update a column when multiple records of another columns of same table matches


I have table as below:

            Input table:
            RequestNumber            TrackName         Date
            -----------------------------------------------------------
            02209                    Middle         2017-05-28 00:00:00
            0263                     Middle         2017-06-29 00:00:00
            0633                     Middle         2017-09-10 00:00:00
            0762                     Back           2017-06-23 00:00:00
            0762                     Front          2017-06-23 00:00:00
            0762                     Middle         2017-06-23 00:00:00
            01839                    Middle         2017-03-09 00:00:00

I need to check, if "RequestNumber" and "Date" is same for "TrackName". if multiple reacords of "RequestNumber" and "Date" matches then I should update the "TrackName" column as "All three" as below output example (in this example there are 3 records matching)

            Output table:
            RequestNumber            TrackName         Date
            -----------------------------------------------------------
            02209                    Middle         2017-05-28 00:00:00
            0263                     Middle         2017-06-29 00:00:00
            0633                     Middle         2017-09-10 00:00:00
            0762                     All three      2017-06-23 00:00:00
            01839                    Middle         2017-03-09 00:00:00

To get the above desigred output this is the SQL I have tried. Howveer, its updating all TrackName to All three.

            UPDATE a 
            SET a.[TrackName] = 'All three'
            FROM Table1 as a
            INNER JOIN 
            (SELECT [RequestNumber], row_number() OVER (ORDER BY [RequestNumber] DESC) as rowNumber
            FROM Table1 ) drRowNumbers ON drRowNumbers.[RequestNumber] = a.[RequestNumber] and drRowNumbers.[Date] = a.[Date]

Hope I have explained this correctly. What am I doing worng? Any query to fix this please?

Note: The records are coming dynamically so can not be hardcoded(if any).

Thanks.


Solution

  • Try This. This will return "All 3" instead of "All Three"-

    SELECT RequestNumber,
    CASE 
        WHEN COUNT(*) = 1 THEN MAX(TrackName) 
        ELSE 'All ' + CAST( COUNT(*) AS VARCHAR) 
    END TrackName,
    Date
    FROM your_table
    GROUP BY RequestNumber,Date