只返回每组oracle中的最大值
Posted
技术标签:
【中文标题】只返回每组oracle中的最大值【英文标题】:Only return the highest value in each group oracle 【发布时间】:2020-06-02 12:24:19 【问题描述】:给定一张桌子:
NAME DATE_OCCURRED
a 2020-05-14 23:48.07
a 2020-05-14 23:48.07
a 2020-05-14 23:48.08
b 2020-05-14 23:48.08
b 2020-05-14 23:48.08
b 2020-05-14 23:48.08
b 2020-05-14 23:48.09
我想为每个NAME
返回记录最多的时间;以及当时存在多少条记录:
NAME MAXCOUNT_PER_SECOND DATE_OCCURRED
a 2 2020-05-14 23:48.07
b 3 2020-05-14 23:48.08
我找到了按 DATE_OCCURRED 和 NAME 对计数进行分组的 SQL:
SELECT COUNT(*) AS COUNT_PER_SECOND, NAME, DATE_OCCURRED FROM TABLE GROUP BY NAME, DATE_OCCURRED ORDER BY NAME ASC, COUNT_PER_SECOND DESC
但我现在想再次选择,只选择每个名称的最大值。我试过了:
SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME FROM (the above query) GROUP BY NAME;
,这可以给我MAXCOUNT_PER_SECOND
和NAME
;但是一旦我尝试并得到哪个DATE_OCCURRED
导致了MAXCOUNT_PER_SECOND
值,我在运行SQL 时最终会出现分组错误;或者我没有得到我期望的结果。
即:
SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME, DATE_OCCURRED FROM (the above query) GROUP BY NAME;
-> Not a GROUP BY expression
SELECT MAX(COUNT_PER_SECOND) AS MAXCOUNT_PER_SECOND, NAME, DATE_OCCURRED FROM (the above query) GROUP BY NAME, DATE_OCCURRED ;
-> 运行,但给我所有日期的结果,而不仅仅是最大值。
【问题讨论】:
【参考方案1】:您可以使用聚合和窗口函数:
select name, date_occured, no_records
from (
select
name,
date_occured,
count(*) no_records,
rank() over(partition by name order by count(*) desc) rn
from mytable
group by name, date_occured
) t
where rn = 1
子查询按name
和date_occured
聚合,计算每组的记录数,并按降序排列具有相同name
的记录组。然后外部查询过滤每个name
的顶部记录。由于我们使用rank()
,因此可能会在结果集中包含可能的排名靠前(如果您不希望这样,请改用row_number()
)。
【讨论】:
以上是关于只返回每组oracle中的最大值的主要内容,如果未能解决你的问题,请参考以下文章
oracle查询表中某一列所有不同分组的某个一列的最大值,并且返回这一行所有列的值。