我试图在一个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 |
答案 0 :(得分:2)
也许......假设table1和table2具有相同的结构。
首先,我生成一个具有1和2的union值的集合,然后我们使用简单的聚合和group by来按名称和年份对值进行求和。
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
答案 1 :(得分:1)
在您发布的查询中,您还需要按年份分组才能获得结果。然后,您可以使用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;
但是,这并没有给出最终结果,因为每个表格中出现的名称(例如“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示例。