我有2张如下表
表1
ID Title Number
001 Student 10
002 Student 20
004 Teacher 25
表2
ID Title Number
001 Researcher 10
002 Student 20
004 Professor 25
我想合并2个表,以便将相同ID的编号加在一起,但标题遵循表1的编号,因此输出如
ID Title Number
001 Student 20
002 Student 40
004 Teacher 50
感谢。
答案 0 :(得分:1)
试试这个。
SELECT t1.ID, t1.Title, (t1.number + t2.number) as total
FROM table1 t1 JOIN table2 t2
ON t1.ID= t2.ID
答案 1 :(得分:0)
一种方法是首先执行两个表中的UNION ALL
,然后计算Number
字段的总和,对ID
进行分组。然后,可以将此结果再次连接回表1,以便在那里使用Title
字段。
SELECT t2.ID, t1.Title, t2.Number
FROM
Table1 t1
INNER JOIN
(
SELECT t.ID, SUM(t.Number) AS Number
(
SELECT t1.ID, t1.Number
FROM Table1 t1
UNION ALL
SELECT t2.ID, t2.Number
FROM Table2 t2
) t
GROUP BY t.ID
) t2
ON t1.ID = t2.ID
答案 2 :(得分:0)
选择a.id,a.title,(a.number + b.number)作为数字从table1作为INNER JOIN table2作为b在a.id = b.id上;