首页 > 解决方案 > 我想如何根据不同的属性汇总所有股票

问题描述

我想用DISTINCT显示属性并汇总每个属性的所有库存。喜欢

+----------+----------+
|    attr  |   stock  |
+----------+----------+
|    Blue  |    61    |
|    Red   |    119   |
+----------+----------+

这是我的桌子1

+----------+----------+
| attrid   |attribute |
+----------+----------+
|        1 |    Blue  |
|        2 |    Blue  |
|        3 |    Red   |
|        4 |    Red   |
+----------+----------+

这是我的桌子2

+----------+----------+
|   stock  | attrid   |
+----------+----------+
|     40   |    1     |
|     21   |    2     |
|     45   |    3     |
|     74   |    4     |
+----------+----------+

标签: mysql

解决方案


连接两个表,对 stock 列求和,然后按属性 ID 分组,如下所示。

select sum(B.stock), A.attribute
from table1 A 
inner join table2 B on (A.attrid = B.attrid)
group by A.attribute

推荐阅读