sql >> Base de Datos >  >> RDS >> Sqlserver

Actualizar los mismos datos de la misma tabla

Podría simplemente agregar un EXISTS porción:

-----create table
CREATE TABLE #Test(ID INT, CAR VARCHAR(30), ACTIVE INT)

INSERT INTO #Test(ID, CAR, ACTIVE)
VALUES
(1, 'AAA-25-35', 0),
(2, 'LDB-25-35', 0),
(3, 'LDB-00-35', 0),
(4, 'LDB-25-35', 0),
(5, 'LDB-00-35', 0),
(6, 'LDC-10-10', 0),
(7, 'LDC-10-10', 0),
(8, 'LDB-00-35', 0)


----update table
;WITH CTE AS
(
  SELECT ROW_NUMBER() OVER(PARTITION BY CAR ORDER BY ID) AS t,
         CAR,
         ACTIVE
  FROM #Test
)

UPDATE CTE
SET ACTIVE = 1
WHERE t=1
AND EXISTS (SELECT 1 FROM CTE c WHERE c.CAR = CTE.CAR GROUP BY CAR HAVING COUNT(*) > 1)

SELECT * 
FROM #Test