SQL高级查询计算组的最大值

时间:2015-03-29 14:20:52

标签: sql ruby-on-rails postgresql activerecord

我想创建一个查询,计算满足以下条件的次数。

我有一个包含多个匹配外键的记录的表。我想只检查每个外键组,如果该键的另一列的最高值出现多次。如果这样做会增加计数。

数据

--------------------------
ID  |  Foreign Key | Value
--------------------------
1   |       1      |   1
2   |       1      |   2 
3   |       1      |   2
4   |       2      |   0
5   |       2      |   2
6   |       2      |   1
7   |       3      |   0
8   |       3      |   1
9   |       3      |   1

我想要的查询应返回数字2.这是因为组1(外键)中的最大值出现两次,值为2.在组2中,最大值为2但只出现一次所以这不会伯爵。然后在组3中,最大值为1,其发生两次,这将使计数增加。因此,计数最终为两个。

2 个答案:

答案 0 :(得分:0)

所有功劳都归功于@Bob的评论,但这里是解决了这个问题的sql。

SELECT Count(1) 
FROM   (SELECT DISTINCT foreign_key 
    FROM   (SELECT foreign_key, 
                   Count(1) 
            FROM   data 
            WHERE  ( foreign_key, value ) IN (SELECT foreign_key, 
                                                     Max(value) 
                                              FROM   data 
                                              GROUP  BY foreign_key) 
            GROUP  BY foreign_key 
            HAVING Count(1) > 1) AS data) AS data; 

答案 1 :(得分:0)

这是一种方法:

select max(num_at_max)
  from (select t.*, count(val) over(partition by fk) as num_at_max
          from tbl t
          join (select max(max_val_by_grp) as max_val_all_grps
                 from (select fk, max(val) as max_val_by_grp
                         from tbl
                        group by fk) x) x
            on t.val = x.max_val_all_grps) x