[英]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 ![]() |
Red![]() |
2 ![]() |
Table 2:表 2:
Color![]() |
Count![]() |
---|---|
Blue![]() |
0 ![]() |
Red![]() |
9 ![]() |
Table 3:表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?什么是有效的 SQL 查询来聚合所有这些表中相同格式的数据? Desired output:
所需的 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: SELECT 颜色,(表 1 计数 + 表 2 计数 + 表 3 计数)作为计数:
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: 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.