mysql - 列出 MySQL 中共享组的最常见项目
问题描述
有一个包含组 ID 和项目的表,如下所示:
group item
-------------
1 A
1 B
1 C
1 D
2 D
2 A
2 B
3 B
3 C
3 D
4 A
4 D
4 E
5 A
5 D
如何检索与指定项目一起找到的最常见项目?在上表中, A最常见的项目是D。
解决方案
您可以自加入、聚合和过滤:
select item, item2 most_frequent_item, cnt
from (
select t1.item item, t2.item item2, count(*) cnt,
rank() over(partition by t1.item order by count(*) desc) rn
from mytable t1
inner join mytable t2 on t1.grp = t2.grp and t1.item <> t2.item
group by t1.item, t2.item
) t
where rn = 1
这仅在 MySQL 8.0 中有效(其中窗口函数可用),并且允许绑定(如果有)(如果您不想要绑定,请使用row_number()
而不是rank()
)。
项目 | most_frequent_item | cnt :--- | :----------------- | --: 一个 | D | 4 乙| D | 3 C | 乙| 2 C | D | 2 D | 一个 | 4 E | 一个 | 1 E | D | 1
在早期版本中,这有点复杂。一个选项使用having
子句:
select t1.item item, t2.item most_frequent_item, count(*) cnt
from mytable t1
inner join mytable t2 on t1.grp = t2.grp and t1.item <> t2.item
group by t1.item, t2.item
having count(*) = (
select count(*) cnt
from mytable t11
inner join mytable t21 on t11.grp = t21.grp and t11.item <> t21.item
where t11.item = t1.item
group by t11.item, t21.item
order by count(*) desc limit 1
)
order by t1.item
推荐阅读
- mysql - MySQL:如何在同一行显示前一天数据和第二天数据
- gradle - JHipster 的 Gitlab CI 失败
- asp.net-core - 为什么回滚后我在 SaveChanges 上收到 DbUpdateConcurrencyException
- c# - 如何在 C# 中标准化花哨的 unicode 字符串?
- java - 从 JPanel 获取课程
- email - 尝试连接到 Gmail 的 SMTP
- javascript - Jquery:第一次点击后停止
- node.js - 试图在 Discord bot 中进行决斗功能,但 while 循环导致致命错误
- python - Pandas.cut() 关于分类值
- mysql - 将 SQL 转换为 DQL