使用Group By时选择Top / Highest计数的SQL

时间:2013-02-11 21:47:07

标签: sql count group-by

任何人都可以帮我处理将返回App_ID最高计数的SQL。我正在运行这个返回以下数据集的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

由于 Dipen

3 个答案:

答案 0 :(得分:4)

在大多数数据库中,您可以使用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,例如相关子查询。

答案 1 :(得分:4)

如果您使用的是SQL-Server 2005或更高版本,则可以使用带有ROW_NumberDENSE_RANK功能的CTE:

WITH CTE AS
(
   SELECT COMP_ID, APP_ID, 
       CNT = COUNT(*) OVER (PARTITION BY APP_ID, COMP_ID) ,
       RN  = ROW_NUMBER() OVER (PARTITION BY APP_ID ORDER BY CNT DESC) 
    FROM APP_ACCT_VIEW
)
SELECT COMP_ID, APP_ID, CNT
FROM CTE
WHERE RN = 1

如果您使用DENSE_RANK,那么如果APP_ID具有与CNT不同的ROW_NUMBER,那么每{{1}}会获得多条记录,而{{1}}总是会为每个组返回一个结果。

答案 2 :(得分:0)

还有一个选择

 ;WITH cte AS
 (
  SELECT COMP_ID, APP_ID, COUNT(*) AS cnt,
         ROW_NUMBER() OVER(PARTITION BY APP_ID ORDER BY COUNT(*) DESC) AS rn
  FROM dbo.APP_ACCT_VIEW
  GROUP BY COMP_ID, APP_ID
  )
  SELECT COMP_ID, APP_ID, cnt
  FROM cte
  WHERE rn = 1

SQLFiddle上的演示