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.
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.
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.
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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With