Reputation: 3822
I've got a many to many table p_to_t
+----------+-----------+-----------+
| p | t | weight |
+----------+-----------+-----------+
| 1 | bob | 40 |
+----------+-----------+-----------+
| 2 | sue | 24 |
+----------+-----------+-----------+
| 3 | bob | 90 |
+----------+-----------+-----------+
| 4 | joe | 55 |
+----------+-----------+-----------+
| 5 | bob | 33 |
+----------+-----------+-----------+
I'm looking to query for value t WHERE p IN(1,2,4,5) while summing the weight for each value of t.
This query: "SELECT t, SUM(weight) AS sWeight FROM p_to_t WHERE p IN(1,2,4,5)";
just adds all the sums to the first "t" selected e.g;
+-----------+-----------+
| t | weight |
+-----------+-----------+
| bob | 152 |
+-----------+-----------+
When what I would like is:
+-----------+-----------+
| t | weight |
+-----------+-----------+
| bob | 97 |
+-----------+-----------+
| joe | 55 |
+-----------+-----------+
Thoughts?
Upvotes: 0
Views: 56
Reputation: 110
Yes you can add just Group by to your actual query. then you will get the below result.
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 |
+-----------+-----------+
Upvotes: 0
Reputation: 7123
SELECT t, SUM(weight) AS sWeight FROM p_to_t WHERE p IN(1,2,4,5) GROUP BY t
Upvotes: 1
Reputation: 60493
Just add a GROUP BY
clause on t
SELECT
t,
SUM(weight) AS sWeight
FROM p_to_t
WHERE p IN(1,2,4,5)
GROUP BY t
By the way, you will also get Sue with these values in the IN clause...
And not 97
for Bob, as 40 + 33
are more often 73
Upvotes: 5