sql - SQL中根据另一列查找某一列值的最大出现次数

标签 sql postgresql

我有下表:

Keyword_name Conference_name
------------|-------------
value1      | conference1
value1      | conference1
value2      | conference1
value3      | conference1
value2      | conference2
value1      | conference3
.........................

现在,我想找到每个 session 关键字的最大出现次数。我怎样才能做到这一点?

期望的结果应该是这样的:

Conference_name | Keyword_maximum_occurrence
conference1     | value1
conference2     | value2

最佳答案

这称为 mode() PostgreSQL 中的有序集合聚合函数:

SELECT 
  Conference_name, 
  mode() WITHIN GROUP (ORDER BY Keyword_name) AS Keyword_maximum_occurrence
FROM my_table
GROUP BY Conference_name

Background on the mode function here .

关于 MODE()(单个结果)与 RANK()(多个结果)的说明

与基于 RANK() 的查询 ( like in GurV's answer here ) 不同,我的答案将根据 ORDER BY 仅返回 first 模式条款。因此,如果有多个关键字出现频率相同,则此答案将仅返回第一个关键字。根据您的要求,这可能仍然没问题。

关于sql - SQL中根据另一列查找某一列值的最大出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41814116/

相关文章:

sql - 使用聚合函数返回的值进行更新

c# - 将日期插入带有日期列的 sql 表中

postgresql - 创建 pgAdmin 4 主键时出现语法错误

mysql - SQL 嵌套查询和子查询

mysql - 为MySQL手动创建@OneToMany脚本

javascript - 在 promise 中链接三个查询

sql - 如何创建在日期更改时更新的 SQL 表

postgresql - Supabase 数据库大小问题

spring - 我如何加密密码将其插入数据库并在比较后何时连接?

postgresql - 无法从 PostgresQL 取消订阅