6

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..???

1
  • is group_id a varchar column? If so, you should convert it into integer and then run MAX() on it. Commented Oct 6, 2012 at 6:01

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

7 Comments

How would this solve the OP's problem? I think GROUP BY is redundant in his case and if the column was integer, it would have returned 1000 which seems to be not the case.
ya it works but mow as per my requirement i changed my table.can u h elp for above issue?
@Baskar what do you changed the table?
@Baskar since your columns is varchar, you need to cast it first to numeric.
my group_id present format is 2-1000 and type is varchar.How to cast?
|
1

You need to add GROUP BY clause.

select max(group_id) from prospect_group where tenant_id=2 group by tenant_ id 

1 Comment

ya it works but mow as per my requirement i changed my table data.can u h elp for above issue?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.