简体   繁体   中英

How to update only MAX column in SQL Server

I want to update the MAX value's status column with static values in SQL Server:

Script to generate sample data:

CREATE TABLE A
(
seq INT,
TrnId NVARCHAR(MAX),
Status NVARCHAR(10)
)

INSERT INTO A VALUES (1,'A1','A')
INSERT INTO A VALUES (2,'A1','A')
INSERT INTO A VALUES (3,'A1','A')
INSERT INTO A VALUES (4,'A1','P')


INSERT INTO A VALUES (1,'B1','A')
INSERT INTO A VALUES (2,'B1','A')
INSERT INTO A VALUES (3,'B1','A')
INSERT INTO A VALUES (4,'B1','P')


CREATE TABLE #temp
(
TrnId NVARCHAR(MAX)
)

INSERT INTO #temp VALUES ('A1')
INSERT INTO #temp VALUES ('B1')

I have TrnId In #temp table and I want to update only the MAX values column for both TrnId as A1 and B1 with status = 'A'

An example without a CTE:

UPDATE A SET A.Status = 'A'
FROM #temp T
INNER JOIN (SELECT TrnId, MAX(seq) as MaxSeq FROM A GROUP BY TrnId) M ON M.TrnId = T.TrnId
INNER JOIN A ON A.TrnId = T.TrnId AND A.seq = M.MaxSeq

One method uses an updatable CTE:

with toupdate as (
      select a.*,
             row_number() over (partition by trnid order by status desc) as seqnum
      from a
     )
update toupdate
    set status = 'A'
    from toupdate join
         #temp t
         on toupdate.trnid = t.trnid
    where seqnum = 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