How can I join these two tables?

I have one table (t1)

id    score
22     1
35     3
51     4

and the other (t2)

id    score
22     2
35     1
10     5

I want to create the following table using an SQL query.

id    score
10      5
22      3
35      4
51      5

i.e. I need to combine an identifier and add ratings together.

Ideal in ANSI SQL.

+3
source share
3 answers
SELECT  id, SUM(score)
FROM    (
        SELECT  *
        FROM    t1
        UNION ALL
        SELECT  *
        FROM    t2
        ) q
GROUP BY
        id
+2
source

Use UNION ALL to combine all the records of both tables into one and GROUP BY to get the sum for each identifier.

SELECT  id, SUM(score)
FROM    (
          SELECT  id, score
          FROM    t1      
          UNION ALL 
          SELECT  id, score
          FROM    t2
        ) t
GROUP BY
        t.ID
+2
source
create table a(id int, score int)
create table b(id int, score int)

insert into a values(1, 10)
insert into a values(2, 5)
insert into b values(1, 15)
insert into b values(3, 20)

select id, sum(score) from 
(select * from a
 union all
select * from b) s
group by id
0

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


All Articles