我的桌子有两列,名称和访问过的国家:
Name Subjects
mike england
maria china
james russia
mike mexico
maria france
laurel england
... ...
现在我想写一个查询,显示访问过两个国家的人数,三,四等,最多十个。
最终结果如下:
Number of countries -> number of people
10 -> 5
9 -> 13
8 -> 24
and so on.
那么我该如何处理呢? 有什么建议吗?
答案 0 :(得分:0)
为您的表考虑以下架构(我将其命名为subject,并且为了唯一键而添加了id列)
CREATE TABLE `subjects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`country` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
以下查询可以达到您想要的结果
SELECT a.c AS num_of_countries, COUNT(*) AS num_of_people
FROM
(SELECT `country`, COUNT(*) AS c FROM subjects GROUP BY 1) a
GROUP BY 1
答案 1 :(得分:0)
试试这个:
SELECT t2.number_of_country,
count(t1.Name) number_of_people
FROM tableName t1
INNER JOIN
(SELECT Name, count(Subjects) number_of_country
FROM tableName
GROUP BY Name) t2 ON t2.Name = t1.Name
GROUP BY t2.number_of_country