NVO NVO - 5 months ago 22
MySQL Question

Get rows with Group BY in MySQL

Let's assume I have the following table:

example table

I need the numbers from the column

'Shares'
ordered by
'Company'
.

So, Example:


ABC, INC: 88624 + 5588 + 442214 + 11233

DEF Corp.: 4556 + 444863 + 44601


Is there a way to do this using MySQL? Or maybe PHP?

Answer

Aggregate function is the best method:

SELECT SUM(shares), company
FROM table_name
GROUP BY company

The SUM() will do the necessary calculation of the same company name. The GROUP BY will show them by company.

If you want specific companies not all (let's say 2 companies only): You can add WHERE Company = "ABC inc" OR "DEF Corp"

Comments