具有独特结果的MYSQL列的总和

时间:2013-09-04 17:22:29

标签: mysql sql group-by sum

我有很多桌子p_to_t

+----------+-----------+-----------+
|   p      |    t      |   weight  |
+----------+-----------+-----------+
|   1      |   bob     |    40     |
+----------+-----------+-----------+
|   2      |   sue     |    24     |
+----------+-----------+-----------+
|   3      |   bob     |    90     |
+----------+-----------+-----------+
|   4      |   joe     |    55     |
+----------+-----------+-----------+
|   5      |   bob     |    33     |
+----------+-----------+-----------+

我正在寻找值t WHERE p IN(1,2,4,5),同时将t的每个值的权重相加。

此查询:"SELECT t, SUM(weight) AS sWeight FROM p_to_t WHERE p IN(1,2,4,5)";只是将所有总和添加到所选的第一个“t”中;例如

+-----------+-----------+
|    t      |   weight  |
+-----------+-----------+
|   bob     |   152     |
+-----------+-----------+

当我想要的是:

+-----------+-----------+
|    t      |   weight  |
+-----------+-----------+
|   bob     |   97      |
+-----------+-----------+
|   joe     |   55      |
+-----------+-----------+

思考?

3 个答案:

答案 0 :(得分:5)

只需在t

上添加GROUP BY子句
SELECT 
 t, 
 SUM(weight) AS sWeight 
FROM p_to_t 
WHERE p IN(1,2,4,5)
GROUP BY t

顺便说一下,您还可以在IN子句中使用这些值获取 Sue ...

对于 Bob 而不是97,因为40 + 33更常见73

答案 1 :(得分:1)

SELECT t, SUM(weight) AS sWeight FROM p_to_t WHERE p IN(1,2,4,5) GROUP BY t

<强> FIDDLE

答案 2 :(得分:0)

是的,您只能将Group by添加到实际查询中。然后你会得到以下结果。

SELECT t, SUM(weight) AS sWeight 
 FROM p_to_t 
WHERE p IN(1,2,4,5)
Group by t;

+-----------+-----------+
|    t      |   weight  |
+-----------+-----------+
|   bob     |   73      |
+-----------+-----------+
|   joe     |   55      |
+-----------+-----------+
|   sue     |   24      |
+-----------+-----------+