计数次数最常见的记录出现在表格中

时间:2014-06-20 10:30:07

标签: sql sql-server

在SQL Server 2012中,我有一个名为Deal_Country的表。此表包含一个名为deal_id的字段,该字段不是主键。相同的deal_id值可以多次出现在表中。

我想知道的是表中最常见deal_id的数字  请参阅下面的示例。

 deal_id
 --------
 ABC12
 DFG34
 DFG34
 KNG10
 ABC12
 PPL11
 ABC12

我想要回答的答案是3,因为最常见的deal_id(ABC12)会显示3次。

我已经尝试了下面的查询,但是我得到了

"cannot perform an aggregate function on an expression containing an aggregate 
 or a subquery."

select max(count(distinct deal_id))
from DEAL_COUNTRY

3 个答案:

答案 0 :(得分:3)

使用order bytop

 select top 1 deal_id, count(*) as numtimes 
 from DEAL_COUNTRY
 group by deal_id
 order by count(*) desc

在MySQL中,您可以使用limit代替top 1

答案 1 :(得分:1)

MySQL解决方案

count首先,将它们从最大值分类为最小值并选择前1个记录。

select deal_id, count(deal_id) deal_count 
  from deal_country
 order by 2 desc 
 limit 1

答案 2 :(得分:1)

这将处理两个交易都位于顶部的情况。

WITH cte AS
(
    SELECT
       deal_id,
       count(*) as cnt 
    FROM DEALS
    GROUP BY deal_id
 )
 ,
cte2 AS (   
   SELECT
     deal_id,
     RANK() OVER (ORDER BY cnt desc) AS RankNumber
   FROM cte

)    
SELECT * FROM cte2 WHERE RankNumber = 1;
编辑:忘掉了TIES。例如

 SELECT TOP 1 WITH TIES
    deal_id,
    COUNT(*) AS cnt 
 FROM DEALS
 GROUP BY deal_id
 ORDER BY COUNT(*) DESC