对 MySQL 中多个表的列求和

Sum columns from multiple tables in MySQL

我试图在一个 SQL 查询中对多个表中的某些列求和,但我似乎得到了错误的结果。我认为我在下面提供的代码有问题。请对此提供任何帮助。

item Names
 | id | name |
 | 1  |  AB  |
 | 2  |  CA  |

table1
| id  | interest | year |
| 1   |   20.00  | 2014 |
| 2   |   30.00  | 2013 |
| 1   |   10.00  | 2013 |

table2
| id  | deposit  | year |
| 1   |   10.00  | 2014 |
| 2   |   10.00  | 2014 |

这是我试过的查询:

    SELECT 
        a.name,
        b.year,
        sum(b.interest) as 'total'
    FROM
        `table1` b
    INNER JOIN
        `item names` a
    ON
        b.id=a.id
    GROUP BY
        b.id

UNION ALL

    SELECT 
        c.name,
        d.year,
        sum(d.deposit) as 'total'
    FROM
        `table2` d
    INNER JOIN
        `item names` c
    ON
        d.id=c.id
    GROUP BY
        d.id

预期结果

更新

我正在尝试查找特定年份和特定项目的利息和存款总额

|name   | year  |   total    |
| AB    | 2014  |    30.00   |
| AB    | 2013  |    10.00   |
| CA    | 2013  |    30.00   |
| CA    | 2014  |    10.00   |

也许...假设 table1 和 table2 具有相同的结构。

首先,我使用一和二的联合值生成一个集合,然后我们使用一个简单的聚合和一个分组依据按名称和年份对这些值求和。

SELECT I.Name, B.year, Sum(B.Total) 
FROM item I
INNER JOIN  
(SELECT * FROM table1 UNION select * FROM table2) B
  on B.ID = I.ID
GROUP BY I.Name, B.Year

在您发布的查询中,您还需要按年份分组才能获得结果。然后,您可以使用 UNION 获取第一组中的所有行以及第二组中的所有行:

SELECT a.name, b.year, SUM(b.interest) AS total
FROM names a
JOIN table1 b ON b.id = a.id
GROUP BY a.name, b.year
UNION
SELECT a.name, c.year, SUM(c.deposit) AS total
FROM names a
JOIN table2 c ON c.id = a.id
GROUP BY a.name, c.year;

但是,这不会为您提供最终结果,因为每个 table 中出现的名称(例如 'AB')将出现两次。一排是一年的存款,一排是一年的利息。要组合这些,只需将上面的用作子查询,对总数求和,然后再次按名称和日期分组:

SELECT name, year, SUM(total) AS total
FROM(
  SELECT a.name, b.year, SUM(b.interest) AS total
  FROM names a
  JOIN table1 b ON b.id = a.id
  GROUP BY a.name, b.year
  UNION
  SELECT a.name, c.year, SUM(c.deposit) AS total
  FROM names a
  JOIN table2 c ON c.id = a.id
  GROUP BY a.name, c.year) temp
GROUP BY name, year;

这是一个 SQL Fiddle 示例。