0

Lets say we have a table Requests with structure:

user_id 
product_id 
count

With entries like:

1 1 5  
1 2 6  
1 1 3
2 1 7
2 1 3
2 2 5

I want to count how much of each product each user has.

And get output like this:

1 1 8
1 2 6
2 1 10
2 2 5
1
  • Edit: removed Wow, that was easy! Thank you!!. There is no need to "thank", just "accept answer" and "up vote" it's the same. Commented Nov 16, 2011 at 14:13

3 Answers 3

2

Use GROUP BY with the SUM aggregate function:

SELECT user_id, product_id, SUM(count) AS total
FROM Requests
GROUP BY user_id, product_id
Sign up to request clarification or add additional context in comments.

Comments

2

Your query will look something like this:

SELECT user_id, product_id, SUM(`count`)
FROM Requests
GROUP BY user_id, product_id

I wouldn't name a field "count" if I had the choice, as it's a SQL function and could cause weird naming conflicts down the road.

Comments

0

You can find a tutorial on how to use GROUP BY here:

You can also find specific information on the syntax and use of GROUP BY in MySQL in the MySQL Manual:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.