SQL查询总结具体条件

时间:2016-10-26 07:12:43

标签: mysql sql

我正在编写SQL查询以根据分配的组总结值。我有数据库像: 表A

+----+--------+
| id | group  |
+----+--------+
|  A1| A      |
|  A2| A      |
|  B1| B      |
+----+--------+

表B:

+----+--------+
| id | Amount |
+----+--------+
|  A1| 10     |
|  A1| 20     |
|  B1| 5      |
|  A2| 10     |
+----+--------+

我希望得到这样的结果:

+----+--------+
| id | Amount |
+----+--------+
|  A1| 40     |
|  B1| 5      |
+----+--------+

仅供参考我使用MySQL作为我的DBMS  预期结果将显示最小ID并添加来自同一组的金额

5 个答案:

答案 0 :(得分:2)

select min(a.id) as id, 
       sum(b.amount) as total
from tableB b
join tableA a on a.id = b.id
group by a.`group`

答案 1 :(得分:1)

简单加入和分组:

SELECT MIN(a.id),sum(b.amount)
FROM TableA a
JOIN TableB b
 ON(a.id = b.id)
GROUP BY a.group

如果您特别希望A1,B1作为ID,请解释此逻辑。

答案 2 :(得分:0)

您是否尝试使用SUM和GROUP BY?

SELECT SUM (Amount) FROM table GROUP BY id

答案 3 :(得分:0)

SELECT 
      (select top 1 A2.id from TableA as A2 where A2.[group] = A.[group]) as id,      
      sum(B.Amount) as Amount
FROM TableA as A
  left join TableB as B on B.id = A.id  
group by A.[group]

此代码在MS SQL 2012上运行。您可以单独验证它是否适用于MYSQL。

答案 4 :(得分:0)

SELECT A.id, SUM(B.amount) as amount 
FROM A
INNER JOIN B ON A.id = B.id
GROUP BY A.group

有关join的更多信息:

MySQL JOIN