gpt4 book ai didi

sql - 按组提取最常见(计数最高)的条目

转载 作者:行者123 更新时间:2023-12-05 01:25:18 25 4
gpt4 key购买 nike

我有下表:

ID       height
personA 182
personA 182
personA 182
personA 192
personA 172
personB 175
personB 175

我想提取此人最常出现的高度,因为我怀疑 192 是一个拼写错误。到目前为止,我有:

select ID, height, count(ID,height) as cnt
from tbl
group by ID, height
having max(cnt);

我想要的输出是:

ID       height
personA 182
personB 175

最佳答案

您可以简单地使用为您的用例设计的模式。请注意,这不会处理关系

select id, mode(height) as height
from t
group by id;

另一种不使用分析函数的替代方法也能处理关系

with cte as
(select id, height, count(*) as cnt
from t
group by id, height)

select id, height
from cte
where (id, cnt) in (select id, max(cnt)
from cte
group by id)

如果您要使用 Lukasz 的回答中巧妙使用的 qualify 子句来实现上述内容,您可以这样做

select id, height
from t
group by id, height
qualify max( count(*) ) over (partition by id) = count(*)

关于sql - 按组提取最常见(计数最高)的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70925880/

25 4 0
文章推荐: powershell - 如何使用哈希表将参数传递给在参数前使用双破折号的 powershell cmd
文章推荐: r - fromJSON 错误 ("employee.json") : not all data was parsed (0 chars were parsed out of a total of 13 chars)
文章推荐: github-actions - JIB 与 GitHub 操作
文章推荐: sql - COPY INTO in snowflake throws 表不存在