MySQL 4 SUM if two rows have the same value on a given column

1.5k Views Asked by At

I'm using an (OLD) MySQL 4.0 database and I need to sum quantities when for two rows, a specific column has the same value.

Example,

So let,s say I have these columns: doc_nr | client_name | article_id | qty

When they are inserted into the database, they are separated into different rows each with quantity 1 (complicated amount of services control background for upper management)

What I want to do is that, for the same article_id, and for the same doc_nr (which imply that it's for the same customer) if the article_id is the same, I want to output the quantity as a SUM of them.

So, for a customer which ordered a quantity of 2 articles, that is then inserted as two separate rows with quantity 1, how do I output quantity 2 again?

1

There are 1 best solutions below

1
On

You could use a GROUP BY query:

SELECT doc_nr, client_name, article_id, SUM(qty) AS qty
FROM yourtable
GROUP BY doc_nr, client_name, article_id

if qty is always 1, instead of SUM(qty) you could just use COUNT(*) that counts the number of grouped rows.