Summing the values ​​of one column from one row from two tables to the third table

This name sounds very confusing, so let me show you what I need.

table1:

name  number
Bob   6
Linda 8
Tina  3

table2:

name  number
Bob   9
Linda 2
Tina  1

I need to summarize the values numberin the third table (which already exists) so that it looks like this:

table3:

name  number
Bob   15
Linda 10
Tina  4

Sorry if this has already been answered, but I searched as best as I could, and all the answers were really specific in the question and did not quite do what I needed.

Edit: table3 currently completely empty. He just shares the same structure as table1and table2.

+4
source share
3 answers

Here's how you do it:

insert into table3 (name, number)
    select t.name, sum(t.number) as totalNumber
    from (
       select name, number from table1 
       union
       select name, number from table2
       union
       select name, number from table3
    ) t
    group by t.name

name, where, group by :

where t.name = 'Bob'
+5

3 , , .

insert into table3 (number) values (select (t1.number + t2.number) from table1 inner join table2 on t1.name = t2.name where t1.name = 'Bob') 

.

+1

your expected result ... !!! (Simple and sorted request)

          INSERT INTO table3 (name,number)
          SELECT t.name, sum(t.number) as number
          FROM (
              SELECT name, number from table1 
              UNION
              SELECT name, number from table2
          ) t
          GROUP BY t.name

Result: -

Table3:

          name    number
          Bob      15
          Linda    10
          Tina     4
0
source

Source: https://habr.com/ru/post/1539398/


All Articles