Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join tables with Aggregate value

I've two tables, named Table-A and Table-B. Please refer given tables . I want to join these after taking the aggregate of 'Value' column in both tables. For eg;

TABLE-A

     Name    Value1
      ABC     10
      ABC     18
      ABC     12
      DEF     5
      XYZ     15
      XYZ     16

TABLE-B

     Name    Value2
      ABC     15
      ABC     5
      XYZ     9

My expected result is,

Result

     Name    Value1   Value2
      ABC      40       20
      DEF      5        0
      XYZ      31       9

Hope you understand my question. Any help will be appreciated.

like image 803
N K Avatar asked Jun 10 '13 05:06

N K


People also ask

Can you GROUP BY an aggregate?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do you aggregate a table in SQL?

use the keyword COUNT to count the number of rows in a column or table. use the keyword AVG to find the mean of a numerical column. use the keyword SUM to find the total of a numerical column when all the values are added together. use the keyword GROUP BY to group by a column in a table.

How Use SUM in inner join in SQL?

SQL SUM() and COUNT() with inner joinThe data from a subquery can be stored in a temporary table or alias. The data of these temporary tables can be used to manipulate data of another table. These two tables can be joined by themselves and to return a result.


1 Answers

Try this one -

SELECT 
      a.Name
    , Value1 = ISNULL(Value1, 0)
    , Value2 = ISNULL(Value2, 0)
FROM (
    SELECT 
          Name
        , Value1 = SUM(Value1)
    FROM dbo.[TABLE-A]
    GROUP BY Name
) a
LEFT JOIN (
    SELECT 
          Name
        , Value2 = SUM(Value2)
    FROM dbo.[TABLE-B]
    GROUP BY Name
) b ON a.Name = b.Name
like image 71
Devart Avatar answered Oct 24 '22 20:10

Devart