Skip to content
Advertisement

SQL Server How to UPDATE with SELECT and GROUP BY clause

Our team uses SQL Server and I wanted to use aggregate function to update one of the columns for the NEW values that are being inserted existing table.

Below is the existing table and values in it.

Requirement came in to ‘Auto Pilot’ for BMW and Tesla only with sequence column incremented in the same carCompany group. Since, Insert statement was easier, I just inserted records and struggling to get the Update statement right.

Below UPDATE statement is INCORRECT. Kindly help here.

Advertisement

Answer

You’re close, just move the correlated subquery into the SET statement:

But note that this only works if there’s only one new record for that car company. I.e., if you had two new Tesla features they’d both be set to 2. You can use a CTE with the RANK function to allow for any number of new values:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement