0

我想编写查询来检查存在多少具有相同值的最小值以及每个类别的计数。表数据如下所示

Id CatId 值
1 1 2.3
2 1 2.3
3 2 1.1
4 1 4.2
5 2 1.5
6 3 8.1
7 1 3.3
8 3 4.2
9 2 1.9

查询应该返回类似的行

CatId min(value) count_with_same_min_value count(CatId)
1 2.3 2 4          
2 1.1 1 3
3 4.2 1 2


谢谢

4

2 回答 2

3

您可以使用子查询来做到这一点:

select c.catid, min(c.value),
       sum(c.value = cmin.minval),
       count(c.CatId)
from category c join
     (select catid, min(value) as minval
      from category
      group by catid
     ) cmin
     on c.catid = cmin.catid
group by c.catid;

select在选择中使用:

select catid, min(value),
       (select count(*) from category c2 where c2.value = min(c.value)),
       count(CatId)
from category c
group by catid;
于 2013-09-13T15:27:04.437 回答
1
 SELECT x.catid
      , MIN(value) a
      , COUNT(y.catid) b
      , COUNT(*) c
   FROM my_table x 
   LEFT 
   JOIN 
      ( SELECT catid
             , MIN(value) min_value 
          FROM my_table 
         GROUP 
            BY catid
      ) y 
     ON y.catid = x.catid 
    AND y.min_value = x.value 
  GROUP 
     BY catid;
于 2013-09-13T15:27:24.970 回答