右键加入两个表后的SUM和组

时间:2016-06-16 02:25:38

标签: c# mysql sql access

我有两张桌子,我需要右边JOIN然后做SUM和Group。



    Table1: PRODUCT_NAME

    -------------------------
    Module_Code | Product_ID
    -----------------------------
    0201        | A
    0202        | A
    0205        | A
    0503        | B
    0507        | B
    -------------------------------

    Table2: SF_PASS
    -------------------------------
    Module_Code | Test_Qty | Phase 
    ---------------------------------
    0201        | 10       | 1
    0201        | 20       | 2
    0201        | 50       | 3
    0202        | 20       | 1
    0202        | 20       | 2
    0202        | 20       | 3
    0503        | 3        | 1
    0503        | 4        | 2
    0503        | 5        | 3

    
I need the result as:
    -------------------------
    Product_ID | Test_Qty
    ---------------------------
    A          | 140
    B          | 12


你能帮忙吗?

1 个答案:

答案 0 :(得分:3)

一个简单的INNER JOIN会:

SELECT
    pn.Product_ID,
    SUM(sp.Test_Qty) AS Test_Qty 
FROM PRODUCT_NAME pn
INNER JOIN SF_PASS sp
    ON sp.Module_Code = pn.Module_Code
GROUP BY
    pn.Product_ID

如果您希望所有产品都显示,即使SF_PASS中没有匹配的行,请将INNER JOIN更改为LEFT JOIN

SELECT
    pn.Product_ID,
    COALESCE(SUM(sp.Test_Qty), 0) AS Test_Qty 
FROM #PRODUCT_NAME pn
LEFT JOIN #SF_PASS sp
    ON sp.Module_Code = pn.Module_Code
GROUP BY
    pn.Product_ID;

ONLINE DEMO