Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a mysql table structure like below:
id, name, city
----------------
1, name1, city1
2, name2, city2
3, name3, city1
4, name4, city1,
5, name5, city2

I want to fetch total rows with max row id for a particular city.

Ex. For city = "city1"
Output should be:
totalrows, max(id), name
3, 4, name4

Ex. For city = "city2"
Output should be:
totalrows, max(id), name
2, 5, name5

How can I get this result in a single query?

What I have tried:

I did tried my self many query but unable to find any query and finally submit the question here.
Posted
Updated 19-Jun-17 13:11pm

You need to use group by to get the initial data and then you can put all of that into a sub-query. The following example is in T-SQL and was tested against SQL Server as I am unable to load MySQL at this time. The syntax may have some minor errors but the principal works:

I created a table called kals84 with your data as per the question and this query returns the values you require:
SQL
select q.cnt, q.mx, k.name, q.city
from kals84 k
inner join (select city, count(*) as cnt, max(id) as mx
from kals84 group by city) q on k.city = q.city and q.mx = k.id
The key to this working is the sub-query
SQL
select city, count(*) as cnt, max(id) as mx
from kals84 group by city
which returns the values
city   cnt      mx
city1	3	4
city2	2	5
You get the name from joining to those results based on the city and the derived mx column
 
Share this answer
 
select distinct Count(Id) over (partition by city) as "Total_rows" ,Max(id) over (partition by city) as "max_id", name
from temp_cp
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900