gpt4 book ai didi

sql - SQL 中的多数函数

转载 作者:行者123 更新时间:2023-12-02 21:30:05 24 4
gpt4 key购买 nike

我正在编写一个 SQL 命令来查找表中的多数值(如果该值在表中出现的次数超过 50%,则该值将作为多数返回)。例如a Emp(姓名、年龄、部门)表中的值:(32, 33, 45, 45 ,45 21, 45)

因此,如果用户想要获得字段年龄的多数值,他将运行命令:

SELECT majority(age) FROM Emp

现在在后端生成的相应 SQL 命令将如下所示:

SELECT age FROM Emp GROUP BY age HAVING COUNT(*) > ((SELECT COUNT(*) FROM Emp) / 2);

此查询返回结果 45。

但是对于像这样的用户查询:

SELECT majority(age), dept FROM Emp GROUP BY dept

然后我不确定如何使用 group by 功能创建类似的查询,还是应该创建其他查询?提前致谢

最佳答案

(假设您正在使用 Oracle - 因为在 MySQL 中您无论如何都无法编写自己的聚合)

我认为你可以使用窗口函数来做到这一点:

这相当于第一个示例:

select distinct age
from (
select age,
dept,
count(*) over () as total_count,
count(*) over (partition by age) as age_count
from emp
)
where age_count >= total_count / 2;

通过简单地将部门添加到分区(组)定义中,这应该可以满足您的需求:

select distinct age
from (
select age,
dept,
count(*) over (partition by dept) as dept_count,
count(*) over (partition by dept, age) as age_count
from emp
)
where age_count >= dept_count / 2;

关于sql - SQL 中的多数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com