skip to Main Content

the base table is TABLE_1.

I want to "join SUM values" from TABLE_2 to TABLE_1 based on columns NUMBER and TOOL like IMAGE below.

IMAGE

I ve tried to use LEFT JOIN but didnt get result like this in IMAGE.
Can someone give me a hint or write query for this?

Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    In the meantime I did it in microsoft sql server management studio. He has "query designer" and he helped me to do it right:

    SELECT Table_1.number, Table_1.tool, SUM(Table_2.value) AS Sum
    FROM Table_1
    LEFT JOIN Table_2 ON Table_1.number = Table_2.number AND Table_1.tool = Table_2.tool
    GROUP BY Table_1.number, Table_1.tool
    

    Thank you anyway, by!


  2. You can achieve this using a LEFT JOIN and SUM function.

    SELECT table_1.NUMBER, table_1.TOOL, SUM(table_2.VALUE) AS SUM
    FROM table_1
    LEFT JOIN table_2 ON table_1.NUMBER = table_2.NUMBER AND table_1.TOOL = table_2.TOOL
    GROUP BY table_1.NUMBER, table_1.TOOL;
    

    This query will join the two tables based on matching NUMBER and TOOL columns, and then group the results by NUMBER and TOOL. The SUM function is used to calculate the sum of values from VALUE column in table_2 for each group.

    db<>fiddle output

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search