SQL Server 2012:根据另一个表的列中的最小值更新列

时间:2015-03-30 21:48:57

标签: sql-server sql-update min

CREATE TABLE #TBLA (id int, numb int, value int)
INSERT INTO #TBLA 
VALUES (1,3,24),
       (1,4,14),
       (2,2,61),
       (2,1,12),       
       (2,3,54)



CREATE TABLE #TBLB (ID int, Value int)
INSERT INTO #TBLB (ID)
VALUES (1),(2)

我想更新#TBLB值列,以便该值与表A中的min(麻木)相关。 预期结果 : TBLB

id value 
1   24
2   12

谢谢!

2 个答案:

答案 0 :(得分:0)

UPDATE #TBLB
SET Value = A.value 
FROM #TBLA A
JOIN 
(select B.ID, min(A.numb)  as mi
from #TBLA A 
join #TBLB B ON a.id = B.id 
GROUP BY B.ID) res 
ON A.id = res.ID and a.numb = res.mi

答案 1 :(得分:0)

;WITH CTE 
AS (
    SELECT *
      ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Numb ASC) rn 
    FROM #TBLA
   )
UPDATE B
 SET B.Value = C.value
FROM #TBLB B 
INNER JOIN CTE C ON B.ID = C.id AND C.rn = 1