2017-02-15 1 views
1

각 행에, 나는 한 열 수량 (부동)과 id를 (int)있다. 그래서 조인을 통해 동일한 ID의 수량 합계를 테이블 1에서 테이블 2 수량으로 인벤토리에 추가하려고합니다. 예.조인과 각 SQL 서버 행을 업데이 트

내 SQL 정보

Table 1     Table 2 
id quantities   id quantities 
1  1     1   0 
1  2     2   0 
2  4     3   0 
2  1   
3  7 

내가 표 1에서 수량을 합계를과 함께 2

원하는 결과 테이블에 테이블을 추가 가입이

Table 1     Table 2 
id quantities   id quantities 
1  1     1   3 
1  2     2   5 
2  4     3   7 
2  1   
3  7 

난 이 코드를 사용하지만 첫 번째 행만 추가합니다.

update i set quantities=i.quantities+sum(s.rent) from inventory i join temp_rent s on i.id=s.itemid 
+0

귀하의 코드는 ID 및 항목 ID에 합류,하지만 당신은 표시되지 않습니다 당신의 테이블입니다. – manderson

답변

1

간단한 조인 및 집계 트릭

Update Table2 
    set quantities = B.Total 
From Tabel2 A 
Join (Select ID 
      ,Total=sum(quantities) 
     From Table1 
     Group By ID 
    ) B 
    on (A.ID=B.ID) 
0

이 무엇을해야해야합니까 ...

CREATE TABLE #table1 (id INT, quantities INT) 

INSERT INTO #table1(id, quantities) 
VALUES (1, 1) 
INSERT INTO #table1(id, quantities) 
VALUES (1, 2)  
INSERT INTO #table1(id, quantities) 
VALUES (2, 4)  
INSERT INTO #table1(id, quantities) 
VALUES (2, 1)  
INSERT INTO #table1(id, quantities) 
VALUES (3, 7)  

CREATE TABLE #table2 (id INT, quantities INT) 

INSERT INTO #table2(id, quantities) 
VALUES (1, 0) 
INSERT INTO #table2(id, quantities) 
VALUES (2, 0)  
INSERT INTO #table2(id, quantities) 
VALUES (3, 0) 

UPDATE #table2 
SET quantities = t1.quantities 
FROM #table2 t2 
    JOIN (
      SELECT id, SUM(quantities) AS quantities 
      FROM #table1 
      GROUP BY id 
     ) t1 ON 
     t2.id = t1.id 

DROP TABLE #table1 
DROP TABLE #table2 
관련 문제