如何嵌套两个count()语句?

时间:2012-06-06 22:30:40

标签: mysql

想象一下一个三列的表格,让我们说TRAVELS包含他们曾去过的NAME列和COUNTRY,以及DATE以便可以是重复的NAME + COUNTRY行。

- >我不想显示实际的NAME值,也不想显示实际的COUNTRY值 - 仅显示计数,仅适用于访问过多个国家/地区的人。

这将是一个这样的列表:

  

| 9 | 2 | 意味着9个人访问了2个国家,
  | 4 | 3 | 意味着4个人访问了3个国家,
  | 2 | 4 | 意味着2个人访问了4个国家,
  等

我对SQL很不好,但我想我需要构建某种嵌套查询:

select count(t1.NAME)
from TRAVELS t1
where (
  select count(distinct COUNTRY) 
  from TRAVELS t2
  where t1.name = t2.name
    and count(t2.COUNTRY) > 1
)

显然这不起作用,但我希望它表明我的一般意图。我一直无法找到关于这种嵌套双重计数的任何内容,虽然一看到它就足够简单了吗?

2 个答案:

答案 0 :(得分:2)

在此处试试:http://sqlfiddle.com/#!2/b0762/3

查询:

select
    count(*) as people,
    countries_visited
from (
    select
      name,
      count(distinct country) as countries_visited
    from travels
    group by name
    having count(distinct country) > 1
) s
group by countries_visited
order by people desc, countries_visited desc

答案 1 :(得分:1)

select country_count, count(*) as people_count 
  from (select name, count(distinct country) as country_count 
          from travels 
         group by name 
        having count(distinct country) > 1)
group by country_count

当然这假设名称是唯一的。如果不是,您可能希望使用user_id代替名称。