Reputation: 10697
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'
Upvotes: 3
Views: 325
Reputation: 1269463
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;
Upvotes: 1
Reputation: 1258
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
Upvotes: 2