Oveys
Oveys

Reputation: 113

Select Max of sum Value in mysql

I have a table in my database like this :

m  | v
-------
1  | 10
1  | 15
1  | 15
2  | 8
2  | 12
2  | 14
3  | 25
3  | 15
3  | 18
4  | 12

I want select maximum of sum v group by m and in first step I create table with this code :

First Code:

select m,sum(v) as v from table group by m

First result:

m  | v
-------
1  | 35
2  | 34
3  | 54
4  | 12

and for select max in this table my code is :

Second Code:

select max(v) as v,m from 
  (select sum(v) as v,m from table group by `m`)ta

Second result:

v  | m
------
54 | 1

Correct result:

v  | m
------
54 | 3

i haven't any idea for solve this problem.

Upvotes: 1

Views: 345

Answers (3)

Aziz Shaikh
Aziz Shaikh

Reputation: 16524

Try this:

select m,sum(v) as v from table group by m ORDER BY v DESC LIMIT 0,1

Upvotes: 2

Girish
Girish

Reputation: 12127

try this query

 SELECT v,m from 
  (SELECT SUM(v) as v, m FROM maxValues GROUP BY `m`) ta
ORDER BY v DESC
LIMIT 1

Upvotes: 1

Junaid S.
Junaid S.

Reputation: 2642

try this

(select max(sum(v)), m as v,m from table group by `m`)

Upvotes: 0

Related Questions