MySQL查询分组数据

时间:2012-11-28 13:12:48

标签: mysql

任何人都可以指导我为以下场景编写MySQL查询。

表格中的数据是这样的,

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

我希望结果像这样,基本上是同一国家同龄城市的所有用户的总和。

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

2 个答案:

答案 0 :(得分:3)

试试这个:;

SELECT country,
       city,
       age,
       count(user_id) AS age_count
FROM user
GROUP BY country,
         city,
         round(age)

答案 1 :(得分:3)

select country, city, age, count(*) age_count
from user 
group by country, city, age