2017-02-02 2 views
1

난 4 개 테이블에 수량 합계를 시도하고 그리고 난 결과가 그림에서 무엇처럼되고 싶어 : 예 : 구매에서 항목 1의 초기 = 10 + 수량 항목 1의 양 = 10 그래서 위의 두 테이블에있는 항목의 합은 20입니다. 이제 다른 테이블에서 동일한 항목 1을 합산하려고합니다. : 15이고 결과는 다음과 같아야합니다 : 20-15 = 5 나는 합계를 시도했습니다.합 MYSQL

select productName, 
sum(initial.quantity)+sum(buy.quantity) as total1 
- 
sum(sale.quantity)+sum(free.quantity) as total2 
from products 
group by productName 

enter image description here

답변

0

필요 없음 GROUP BY에 대해서만 JOIN 테이블을 사용하고 수학을 사용하십시오.

SELECT i.productid, 
(i.quantity + b.quantity) - (s.quantity + f.quantity) AS quantity 
FROM initial i 
INNER JOIN buy b ON i."product id" = b."product id" 
INNER JOIN sale s ON i."product id" = s."product id" 
INNER JOIN free f ON i."product id" = f."product id" 
+0

인사 ! 그룹별로 내가 틀린 결과를 얻었고 그룹없이 내가 item1 item1 item1을 얻었습니다. 그리고 아직 합계가 없습니다. –

0

당신은 하나 개의 컬럼으로 작성해야합니다 (10 + 10)와 같은

- 당신이 및 SUM에 의해 그룹을 사용하는 것보다 여러 번 동일한 제품이있는 경우 (10 + 5)
그렇지 않으면 제거하십시오.

select products.PRODUCT_ID, 
    (sum(initial.quantity)+sum(buy.quantity))-(sum(sale.quantity)+sum(free.quantity)) as 
    from products join initial on products.product_id=initial.product_id 
    join free on products.product_id=free.product_id 
    join buy on products.product_id=buy.product_id 
    join sale on products.product_id=sale.product_id 
    group by products.PRODUCT_ID 
+0

은 (10 + 10) - (10 + 5) 네가 정확하게 원하는 것입니다. 귀하의 exampl에서 올바른 결과를 얻지 못했습니다 –

+0

@AntiAtlasDev 당신은 지금 실행할 수 있습니까? –

+0

안녕하세요! 그룹별로 내가 틀린 결과를 얻었고 그룹없이 내가 item1 item1 item1을 얻었습니다 ...... 그리고 아직 합계가 없습니다 –

1

당신의 테이블은 반드시 모든 테이블의 모든 항목에 대한 값이없는 경우 (즉, 초기 값을 가지고 있지만, 아직 판매),이처럼 할 안전하지 않을 것이다 :

select p.productName, sum(q.iquantity)+sum(q.bquantity) - sum(q.squantity) - sum(q.fquantity) as 'quantity' 
from products p 
    join (
    select product_id, quantity as iquantity, 0 as bquantity, 0 as squantity, 0 as fquantity 
    from initial 
    union 
    select product_id, 0, quantity, 0, 0 
    from buy 
    union 
    select product_id, 0, 0, quantity, 0 
    from sale 
    union 
    select product_id, 0, 0, 0, quantity 
    from free 
) as q on q.product_id = p.product_id 
group by p.productName 
+0

내가 바로 제품 이름을하지만 잘못된 값을 가지고 .. 그것은 내가 원하는하지만 거의 여전히 잘못된 총을 받고있다 –

+0

노동 조합은 어떻게 될지 모르겠지만? –

+0

내가 받아 들일 정답을 얻을 때까지 나는 투표 할 것이다 –