【问题标题】:Count highest number of co-occurrences of a value in another column (MySQL)计算另一列中值的最高共现次数(MySQL)
【发布时间】:2021-10-10 13:54:54
【问题描述】:

我有一张这样的桌子:

----------------
| ID | Author |
----------------
| 24 | Cathy  |
| 24 | NULL   |
| 24 | NULL   |
| 24 | Thomas |
| 70 | Cathy  |
| 70 | NULL   |
| 99 | Lisa   |
----------------

想象一下,Cathy 的所有ID 与其他Authors 共同出现的频率。

结果应该是4 共同作者(3x NULL + 1x Thomas)。

现在我想找出哪个Author(谁IS NOT NULL)的共同作者数量最多,这可能会导致如下结果:

---------------------------------
| Author | Number of Co-Authors |
---------------------------------
| Cathy  |           4          |
| Thomas |           3          | 
| Lisa   |           0          |
---------------------------------

在 MySQL 中怎么可能?感谢您的帮助!

【问题讨论】:

  • 您是否有理由接受了一个甚至没有运行的答案:dbfiddle.uk/…
  • @forpas 另一个问题将是GROUP BY author,这是模棱两可的,但由于答案包括额外的列,看起来这里涉及读心术。我们永远不会知道原因。
  • @forpas,您指出这一点很有趣。是的, astentx 是正确的,在我的实际情况下,有更多的列,更多的“内部连接”等,并且将 berihulel 的解决方案适应我的情况是最容易为我工作的解决方案(是的,它确实有效 - 奇怪! )。
  • @anpami 很有趣。你的表中有列 paper_id 吗?我在你的问题中没有看到它。如果你真的拥有它,berihulel 是怎么知道的?如果不是,您是如何调整包含假想列的解决方案的?
  • @forpas,不,我的表中没有 paper_id 列。不知道为什么berihulel插入它(现在好像被删除了?)。解释整个表格太复杂了,但是我使用的查询,基于 berihulel,现在看起来像这样:SELECT x.orcid, x.family, x.given, COUNT(DISTINCT(y.orcid)) total FROM aureg x LEFT JOIN aureg y ON y.orcid <> x.orcid AND y.doi = x.doi INNER JOIN preg ON preg.doi = x.doi WHERE x.orcid IS NOT NULL AND y.orcid IS NOT NULL AND preg.date >= '2021-01-01' AND preg.date <= '2021-06-30' GROUP BY orcid ORDER BY total DESC

标签: mysql sql count


【解决方案1】:

您可以使用自联接和条件聚合来做到这一点:

SELECT t1.Author, 
       SUM(t2.ID IS NOT NULL) Number_of_Co_Authors
FROM tablename t1 LEFT JOIN tablename t2
ON t2.ID = t1.ID AND (t2.Author <> t1.Author OR t2.Author IS NULL)
WHERE t1.Author IS NOT NULL
GROUP BY t1.Author
ORDER BY Number_of_Co_Authors DESC;

请参阅demo

【讨论】:

    【解决方案2】:

    你可以使用窗口函数:

    select author, sum(num_coauthors)
    from (select t.*, count(*) over (partition by id) - 1 as num_coauthors
          from t
         ) t
    where author is not null
    group by author;
    

    count(*) - 1 是每个 id 的共同作者数量。也就是说,它是“其他”行数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 2019-03-27
      • 2022-06-16
      • 2020-06-02
      • 2021-04-12
      • 2021-06-07
      相关资源
      最近更新 更多