Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
mbr table

eid     mid
1       15           for eid 1, mid 14 is the min value
1       14
2       18           for eid 2, mid 17 is the min value
2       17
3       19           for eid 3, mid 19 is the min value
3       20

nm table

mid     nmid
15      100
14      104
18      109
17      108
19      999
20      110


expected output

nm table

mid     nmid
14      100   
14      104
17      109   
17      108
19      999
19      110    


for eid 1,mid 14 is min compared to 15 so it should update 15 to 14 in nm table 
for eid 2,mid 17 is min compared to 18 so it should update 18 to 17 in nm table
for eid 3,mid 19 is min compared to 20 so it should update 20 to 19  in nm table


What I have tried:

i tried with logic of selecting max mid from mbr table and select min mid from nm table and use update query to update max to min.it is updating every thing.
can you please help[ on this.

please let me know if any information needed
Posted
Updated 4-Feb-20 9:43am

1 solution

Check this out:

SQL
DECLARE @mbr TABLE(eid INT, mid INT)
INSERT INTO @mbr(eid, mid)
VALUES(1, 15), (1, 14), (2, 18),
(2, 17), (3, 19), (3, 20)

DECLARE @nm TABLE(mid INT, nmid INT)
INSERT INTO @nm(mid, nmid)
VALUES(15, 100), (14, 104), (18, 109),
(17, 108), (19, 999), (20, 110)

UPDATE t1
SET t1.mid = t2.minmid
FROM @nm AS t1
    INNER JOIN (
		SELECT eid, mid, MIN(mid) OVER(PARTITION BY eid ORDER BY mid) AS minmid
		FROM @mbr
	) AS t2 ON t1.mid = t2.mid

SELECT *
FROM @nm


Result:
mid	nmid
14	100
14	104
17	109
17	108
19	999
19	110


For further details, please, see: How do I UPDATE from a SELECT in SQL Server? - Stack Overflow[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900