基于条件SELECT的COUNT

时间:2017-09-27 16:53:21

标签: mysql sql select count

我有一个包含两个变量的表,每个变量出现一次,每个变量出现一次:

Customer        City
Bob             New York
Bob             Denver
Bob             Denver
Greg            Denver
Greg            Denver
Greg            New York

示例:

SELECT Customer FROM tableName WHERE COUNT( SELECT Customer,City FROM tableName)=1;

我想为每个独特的客户名称获取独特的城市,并计算客户拥有的城市数量。你如何在mysql中做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用distinct来电中修改的count

SELECT   customer, COUNT(DISTINCT city)
FROM     tablename
GROUP BY customer

答案 1 :(得分:0)

我不确定您是希望为每个客户重复一个城市还是不同城市的总数,因此我将同时考虑这两个值:

select Customer, City, count(City) as CityCount, TotalDistinctCities
from CustomerCities
join (select Customer as cust, count(distinct City) as TotalDistinctCities
  from CustomerCities
  group by Customer)
as CityCount on cust=Customer   
group by Customer, City, TotalDistinctCities