简体   繁体   中英

Aggregating data from multiple tables of same format in SQL

I have 5 simple tables, that are all the same format. Eg: Table 1:

Color Count
Blue 1
Red 2

Table 2:

Color Count
Blue 0
Red 9

Table 3:

Color Count
Blue 3
Red 1

etc.

What is an efficient SQL query to aggregate the data from all these tables with the same format? Desired output:

Color Count
Blue 4
Red 12

My current idea is to simply join these tables on "Color", and then sum together the values from each column:

Color Table 1 Count Table 2 Count Table 3 Count
Blue 1 0 3
Red 2 9 1

SELECT Color, (Table 1 Count + Table 2 Count + Table 3 Count) as Count:

Color Count
Blue 4
Red 12

I know there must be a more efficient way to do this without having to join by color first. How can this be done?

Union works faster:

SELECT Color, sum(Count) 
FROM (
SELECT Color, Count FROM Table 1 
UNION ALL
SELECT Color, Count FROM Table 2 
UNION ALL
SELECT Color, Count FROM Table 3 
) t
GROUP BY Color

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM