NVO
NVO

Reputation: 2713

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?

Upvotes: 3

Views: 96

Answers (8)

John
John

Reputation: 70

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"

Upvotes: 3

ScaisEdge
ScaisEdge

Reputation: 133370

If you want to list all the SHARES, you can use group_concat and group by:

 select company, group_concat(SHARES) 
 from my_table 
 group by company 

If you want the sum of share, use:

 select company, sum(SHARES) 
 from my_table 
 group by company 

Upvotes: 1

Passionate Coder
Passionate Coder

Reputation: 7294

use this query

select COMPANY,SUM(SHARES) from table_name group by COMPANY

Upvotes: 1

user6474402
user6474402

Reputation: 21

SELECT COMPANY,SUM(SHARES) FROM <TABLE> group by COMPANY;

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269973

If you want the sum, use sum(). If you want a list, then use group_concat():

select company,
       sum(shares) as sum_shares,
       group_concat(shares separator '+') as list_shares
from t
group by company;

The separator keyword allows you to put in a +.

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41437

u can use aggregation function SUM() in the sql

select COMPANY,SUM(SHARES)
from ur_table
group by COMPANY

Upvotes: 1

Mahesh Madushanka
Mahesh Madushanka

Reputation: 2998

USE GROUP BY

SELECT COMPANY,SUM(SHARES) FROM <TABLE> group by COMPANY;

Upvotes: 2

Ankit Sharma
Ankit Sharma

Reputation: 4071

Use below mentioned query

select COMPANY, sum(shares) from table_name group by COMPANY ;

And if you don't want the sum and only need it for display, use:

select COMPANY, GROUP_CONCAT( shares SEPARATOR '+' )from     
table_name group by COMPANY 

Upvotes: 1

Related Questions