Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Maximum value of a column in mysql DB

Tags:

sql

mysql

My DB table column values are

tenant_ id  group_id
2           2-100
2           2-111
1           1-222
1           1-888
2           2-999 
2           2-1000

Query :

select max(group_id) from prospect_group where tenant_id=2

I have used the above query to get the max value for tenant_id=2 but it returns the value as 999 instead of 1000. How to get 1000 as the max value.??? Can anyone help me..???

like image 303
Baskar Avatar asked Oct 06 '12 05:10

Baskar


People also ask

How do you SELECT the highest value in a column in SQL?

The MAX() function returns the largest value of the selected column.

How do I find the greatest number in MySQL?

MySQL MAX() Function The MAX() function returns the maximum value in a set of values.

Can we use Max on a column?

The MAX() function can be used on the string column. For example, the following uses the MAX() function on the LastName column of the Employee table. It will sort the column alphabetically and the last value will be returned.


1 Answers

You need to have GROUP BY clause

SELECT tenant_ID, MAX(CAST(group_ID AS SIGNED))
FROM tableName
-- WHERE  tenant_id=2 -- uncomment this if you select only for specific tenant_ID
GROUP BY tenant_ID

try it by replacing to an empty char.

SELECT tenant_ID, 
       MAX(CAST(REPLACE(group_ID, CONCAT(tenant_ID, '-'), '')  AS SIGNED)) maxGID
FROM tableName
-- WHERE  tenant_id=2 -- uncomment this if you select only for specific tenant_ID
GROUP BY tenant_ID

SQLFiddle Demo

like image 94
John Woo Avatar answered Nov 10 '22 10:11

John Woo