如何在PostgreSQL中选择最大计数

时间:2015-06-15 10:29:45

标签: sql postgresql group-by

我在PostgreSQL中有以下架构的表:

Category    |   Type 
------------+---------
A           |   0 
C           |   11 
B           |   5 
D           |   1 
D           |   0 
F           |   2   
E           |   11 
E           |   9 
.           |   . 
.           |   .

如何选择类别最大类型?以下是我的全部内容:

SELECT 
    category, 
    type, 
    COUNT(*)
FROM 
    table
GROUP BY 
    category, 
    type
ORDER BY 
    category, 
    count 
    DESC

我的预期结果是这样的:

  

Cat | Type | Count
  -------- + ------- + ------

     

A | 0 | 5

     

B | 5 | 30

     

C | 2 | 20

     

D | 3 | 10

这是每个类别中出现最大值的类型,包含该类型的计数。

5 个答案:

答案 0 :(得分:3)

您可以使用以下查询:

SELECT category, type, cnt
FROM (
   SELECT category, type, cnt,
          RANK() OVER (PARTITION BY category 
                       ORDER BY cnt DESC) AS rn
   FROM (
      SELECT category, type, COUNT(type) AS cnt
      FROM mytable
      GROUP BY category, type ) t
) s
WHERE s.rn = 1

以上查询使用您在OP中发布的自己的查询,并对其应用RANK()窗口函数。使用RANK(),我们可以指定来自初始查询的具有最大COUNT(type)值的所有记录。

注意:如果有多个类型具有特定类别的最大出现次数,则上述查询将返回所有的类型,如使用RANK的结果。

Demo here

答案 1 :(得分:2)

如果我理解正确,你可以使用窗口功能:

SELECT category, type, cnt
FROM (SELECT category, type, COUNT(*) as cnt,
             ROW_NUMBER() OVER (PARTITION BY type ORDER BY COUNT(*) DESC) as seqnum
      FROM table
      GROUP BY category, type
     ) ct
WHERE seqnum = 1;

答案 2 :(得分:0)

SELECT 
    category, 
    type, 
    COUNT(*)
FROM 
    table
GROUP BY 
    category, 
    type
HAVING 
    COUNT(*) = (SELECT MAX(C) FROM (SELECT COUNT(*) AS C FROM A GROUP BY A) AS Q)

EDITED: 我向读者道歉,

COUNT(*) = (SELECT MAX(COUNT(*)) FROM table GROUP BY category,type) 

是ORACLE版本,postgresql版本是:

COUNT(*) = (SELECT MAX(C) FROM (SELECT COUNT(*) AS C FROM A GROUP BY A) AS Q)

答案 3 :(得分:-2)

SELECT类别,MAX(Occurence) FROM(SELECT t.category as category,Count(*)AS Occurence FROM table t);

答案 4 :(得分:-2)

SELECT 
    category, 
    type, 
    COUNT(*) AS count
FROM 
    table
GROUP BY 
    category, 
    type
ORDER BY 
    category ASC