2

can anyone please guide me with writing MySQL query for following scenario.

The data in table is like this,

Table Name: user

user_id     country     city            age
----------------------------------------------
1           India       Mumbai          22
2           India       Mumbai          22
3           India       Delhi           22
4           India       Delhi           23
5           India       Chennai         23
6           China       Beijing         20
7           China       Beijing         20
8           China       Shanghai        20
9           USA         New York        30
10          USA         New York        30
11          USA         New York        30
12          USA         Los Angeles     31
13          USA         Los Angeles     31
14          USA         Los Angeles     40

I want result to be like this which is basically sum of all users in particular country's city having same age.

country     city            age     age_count
----------------------------------------------
India       Mumbai          22          2
India       Delhi           22          1
India       Delhi           23          1
India       Chennai         23          1
China       Beijing         20          2
China       Shanghai        20          1
USA         New York        30          3
USA         Los Angeles     31          2
USA         Los Angeles     40          1
0

2 Answers 2

3

Try this :;

SELECT country,
       city,
       age,
       count(user_id) AS age_count
FROM user
GROUP BY country,
         city,
         round(age)
Sign up to request clarification or add additional context in comments.

10 Comments

One more thing what if age has some discrepancy e.g. some columns it has 22 other have 22.0. Any way to solve this?
You can typecast the age field, do you want me to modify?
Yes that would be of great help. Also I want to order rows by age_count but country, city display should remain as it is.
Have updated my query, but it will slow down your execution since if there is an index in city, it wont be considered
I tried this before your update, I tried this before your update, Select country, city, Cast(age as UNSIGNED) as age, count(user_id) as age_count from user group by country, city, age But didn't worked. Anyway thanks for the help.
|
3
select country, city, age, count(*) age_count
from user 
group by country, city, age

1 Comment

Someone else is playing with ratings. Your query is just little slower than Sashi Kant's query. Fetching 10000 rows, Your query: 603.99 secs Sashi Kant query: 586.27 secs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.