使用 Group By 时选择最高/最高计数的 SQL

标签 sql count group-by

任何人都可以帮助我使用 SQL 来返回 App_ID 的最高计数。我正在运行这个返回以下数据集的 SQL。

SELECT COMP_ID, APP_ID, count(*) as cnt 
FROM APP_ACCT_VIEW
GROUP BY COMP_ID, APP_ID

COMP_ID APP_ID                    CNT
cpo1000c    AT                    999
cpo1kact    AT                    895
cpo1kact    CPOPYMTS_Administrative    1020
cpo1000c    CPOPYMTS_HighValue           1900
cpo1kact    CPOPYMTS_HighValue           1020
cpo1000c    CPOPYMTS_Internal            1999
cpo1kact    CPOPYMTS_Internal            1020
cpo1kact    IRCDR                     1020
cpo1000c    IRCDR                     50

但我需要 SQL 返回每个 APP_ID 的顶部/最高 cnt,并且需要输出看起来像这样。

COMP_ID APP_ID                    CNT
cpo1000c    AT                    999
cpo1kact    CPOPYMTS_Administrative    1020
cpo1000c    CPOPYMTS_HighValue           1900
cpo1000c    CPOPYMTS_Internal            1999
cpo1kact    IRCDR                     1020

谢谢 迪彭

最佳答案

在大多数数据库中,您可以使用 row_number() 函数来执行此操作:

select comp_id, app_id, cnt
from (select t.*, row_number() over (partition by app_id order by cnt desc) as seqnum
      from (SELECT COMP_ID, APP_ID, count(*) as cnt
            FROM APP_ACCT_VIEW
            GROUP BY COMP_ID, APP_ID
           ) t
     ) t
where seqnum = 1

如果这不可用,则必须以其他方式计算 seqnum,例如相关子查询。

关于使用 Group By 时选择最高/最高计数的 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14821450/

相关文章:

mysql - SQL - where 子句中的未知列

php - MySql 计算日期行中包含 (NULL) 和/或 '0000-00-00' 值的所有元组

分组的两列的MySQL计数

r - 组不互斥时类似于 group_by 的功能

r - R 中带有 group_by 的多个条件语句?

mysql - 将子查询转换为连接查询

sql - 有没有办法使一列的可为空性取决于另一列的可为空性?

php - 获取表中的所有记录

python - pandas hub_table 返回空数据框

spring - 如何在 MongoRepository 上创建计数查询