简体   繁体   中英

Update same data from the same table

I have a table that has registration of several CAR (repeated and not repeated), so I intend to update a field (active) of all repeated registrations leaving 1 more recent line.
Exemple of table data:

在此处输入图像描述

I want my data to be like this:

在此处输入图像描述

I tried to make this code, but it is not working correctly. Because updated the first row

    -----create table
 create table dbo.test( id int, CAR varchar(30), ACTIVE int)
    
 insert into dbo.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)
    
  select * from dbo.test
    
  ----update table
  WITH CTE AS
  (
      SELECT 
          row_number() over (partition by CAR order by id) as t
          , CAR , ACTIVE
      FROM dbo.test
  )
  update CTE
  SET ACTIVE = 1
  WHERE t=1 
    
  select * from dbo.test

You could just add an EXISTS portion:

-----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

You can use count analytical function in your query as follows:

WITH CTE AS
  (
      SELECT 
          row_number() over (partition by CAR order by id) as t
          , count(*) over (partition by car) as cnt
          , CAR , ACTIVE
      FROM dbo.test
  )
  update CTE
  SET ACTIVE = 1
  WHERE t=1 and cnt>1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM