mysql - SQL B在A中出现了多少次

标签 mysql sql

我有一个问题,我已经花了 3 个多小时来解决。事情是这样的。 下面是包含animal_id 和birds_id 列的表:

animal_id | bird_id
      1    |    1
      3    |    3
      5    |    2
      2    |    1
      6    |    1

我需要编写一个 SQL 查询来计算鸟的数量,即鸟出现在多少个动物中。 输出应该是:

Number of Animals | Number of Birds
         3        |      1
         1        |      2         

说明:上面的输出表明 第 1 行:Birds 中的一个元素 (Bird_id:1) 在 Animals 中出现了 3 次。 第 2 行:Birds 中的两个元素(Bird_id:2 和 Bird_id:3)各在 Animals 中出现一次。

到目前为止我的工作:尽管付出了所有的努力,我只能做这么多:(

SELECT COUNT(*), COUNT(DISTINCT bird_id) AS D FROM myTable GROUP BY bird_id;

到目前为止的输出:

 3   |   1
 1   |   1
 1   |   1

我不太擅长 SQL 查询。有人可以帮我解决这个问题吗?

最佳答案

试试这个:

SELECT `Number of Animals`, 
       COUNT(*) AS `Number of Birds`
FROM (
  SELECT bird_id, COUNT(*) AS `Number of Animals`
  FROM mytable
  GROUP BY bird_id ) AS t
GROUP BY `Number of Animals`

您需要再进行一级聚合才能获得所需的结果。

Demo here

关于mysql - SQL B在A中出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35174132/

相关文章:

mysql - java.sql.SQLNonTransientConnectionException : Public Key Retrieval is not allowed in jhipster docker production for monolithic project

php - 按 DATEPART() 选择行

MySQL - 根据另一个字段仅选择一次值

MySQL include count 不返回计数为零的行

php - 在codeigniter中将密码保存到数据库

mysql - Nodejs更改mysql查询中的全局变量

mysql - 如何使用 SQL 选择特定字段的重复行,并允许存在时间差?

sql - 经典 ASP 站点在移动服务器后抛出日期转换错误?

sql - 理解内部查询的总结

MySQL 简单插入查询在 "query end"步骤上变慢