【问题标题】:How to count the number of rows matching certain values?如何计算匹配某些值的行数?
【发布时间】:2015-02-13 16:44:59
【问题描述】:

其实我现在有一张桌子:

[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. 

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

【问题讨论】:

  • 使用COUNT(*)GROUP BY 获取每个城市的人数。
  • 到目前为止,您是否尝试过任何查询?
  • 我试过了,但可能有问题。 select * from Person where (select count(*) from Person group by City)>6

标签: mysql sql


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    相关资源
    最近更新 更多