简体   繁体   English

从 SQL 中的多个相同格式的表中聚合数据

[英]Aggregating data from multiple tables of same format in SQL

I have 5 simple tables, that are all the same format.我有 5 个简单的表格,它们都是相同的格式。 Eg: Table 1:例如:表 1:

Color颜色 Count数数
Blue蓝色的 1 1
Red红色的 2 2

Table 2:表 2:

Color颜色 Count数数
Blue蓝色的 0 0
Red红色的 9 9

Table 3:表3:

Color颜色 Count数数
Blue蓝色的 3 3
Red红色的 1 1

etc.等等

What is an efficient SQL query to aggregate the data from all these tables with the same format?什么是有效的 SQL 查询来聚合所有这些表中相同格式的数据? Desired output:所需的 output:

Color颜色 Count数数
Blue蓝色的 4 4
Red红色的 12 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表 1 计数 Table 2 Count表 2 计数 Table 3 Count表 3 计数
Blue蓝色的 1 1 0 0 3 3
Red红色的 2 2 9 9 1 1

SELECT Color, (Table 1 Count + Table 2 Count + Table 3 Count) as Count: SELECT 颜色,(表 1 计数 + 表 2 计数 + 表 3 计数)作为计数:

Color颜色 Count数数
Blue蓝色的 4 4
Red红色的 12 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: Union 工作得更快:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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