0

我有一个多对多表 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      |
+-----------+-----------+

想法?

4

3 回答 3

5

只需GROUP BY在 t 上添加一个子句

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 + 3373

于 2013-09-04T17:24:01.423 回答
1
SELECT t, SUM(weight) AS sWeight FROM p_to_t WHERE p IN(1,2,4,5) GROUP BY t

小提琴

于 2013-09-04T17:24:10.067 回答
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      |
+-----------+-----------+
于 2013-09-04T17:40:02.437 回答