The union of the two tables calculates the sum of the same field

Source: Internet
Author: User

There are two tables
Each table has two fields: Id num.
Table A Value
Id num the value ID num of Table B
A 5 B 15
B 10 C 20
C 15 d 20
D 20 E 30
Use an SQL statement to obtain the results of the two tables.
Result Value
Id num
A 5
B 25
C 35
D 40
E 30

SELECT `id`, SUM(`num`) FROM (SELECT * FROM `b` UNION ALL SELECT * FROM `a` ) as new_table GROUP BY `id`

Select * from B Union all select * from a first merges two tables and returns the Union set. The select columns values of the two tables A and B must be the same.

Then sum by group

The union of the two tables calculates the sum of the same field

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.