如何计算匹配特定值的行数?

时间:2015-02-13 16:44:59

标签: mysql sql

实际上我现在有一张桌子:

[Person Table]:
ID  Name    age     City
====================================

1   Jack    14    New York
2   Mike    15    LA
3   Ben     16    Beijing
?           
100 Lee     32    Singapore

(total record = 100)
(Id is Primary Key) 

请提供一个SQL脚本来查询客户他/她的城市在表格中出现的次数大于或等于6。

示例:

The number of customer that live in New York is 10
The number of customer that live in LA=5 
The number of customer that live in Beijing=6. 

因此,在此示例中,输出应该是仅限居住在纽约和北京的所有客户。

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

select * from customers 
  join (select city from customers group by city having count(*) >= 6) 
    as city_count
    on customers.city = city_count.city;

您所做的只是创建一个包含六个或更多客户的城市列表,然后使用它来过滤原始客户表。

Link to SQL Fiddle - using 2 as the threshold