mysql - MySQL:两个 COUNT 的总和(按不同的值)
问题描述
我的 MySQL 表保存引用。每行是一个引用,如下所示:
A = citer
, B = cited
(即 A 引 B)。
我知道如何获取 (1) 谁最常引用 A,以及 (2) 谁最常引用 A:
/* (1) who cited A most often? */
SELECT citer,COUNT(citer) AS citations1 FROM `table` WHERE cited='A' GROUP BY citer ORDER BY citations1 DESC
/* (2) whom did A cite most often? */
SELECT cited,COUNT(cited) AS citations2 FROM `table` WHERE citer='A' GROUP BY cited ORDER BY citations2 DESC
现在我想要得到这两个统计数据的总和(citations1
+ citations2
),这样我就知道谁与 A 的总引用链接最多。
示例:如果 B 引用 A 五 (5) 次,A 引用 B 三 (3) 次,则 AB 链接的总和为八 (8)。
使用 MySQL 公式可以实现吗?谢谢您的帮助!
解决方案
你可以这样写:
select person, (sum(citers) + sum(citeds)) as total
from ((select citer as person, count(*) as citers, 0 as citeds
from citations
where cited = 'A'
group by citer
) union all
(select cited, 0, count(*) as citeds
from citations
where citer = 'A'
group by cited
)
) c
group by person
order by total desc;
这个问题有点棘手。如果您尝试使用 a join
,您将排除具有最多引用链接的人只是“引用者”或“被引用”的可能性。
推荐阅读
- c - c中的getchar()如何处理字符串输入
- r - 使用 unique(data.table) 或 distinct (dplyr) 和部分 gsub 删除行
- mysql - 计算行数和连接表
- git - 从本地删除但作为用户分支存在于repo中时如何从git repo下载分支
- php - 如何列出属于自定义分类的帖子类别
- forms - 如何验证表单字段是否为空
- css - 如何使用 css 编辑材料 ui 表中的行高
- r - 提取固定效应系数时与“EXPR 必须是长度为 1 的向量”相关的错误
- etl - Pentaho 连接到 Sisense elasticCube
- sql - 与关系返回所有行,最大为一列 Sql Sever