使用MIN和COUNT

时间:2012-11-24 17:51:47

标签: sql oracle aggregate-functions oracle-sqldeveloper top-n

你能给我一个使用min并计算相同查询的例子吗?例如,在此表中,我想知道具有奇数代码的工作人员数量较少(1代码为5)。

 Table Workers
      Code
       1
       2
       2
       2
       3
       3
       1
       5

感谢。

4 个答案:

答案 0 :(得分:1)

您需要一个子查询来查找最小值,然后使用该子查询再次查询计数:

select code, count(*)       -- get the count for the code found in the subquery
from workers
where code = (
    select min(code)        -- return the minimum code found
    from workers
    where mod(code, 2) = 1) -- only odd codes
group by code;              -- group by the non-aggregated column(s0

编辑:

从评论中,您似乎想要最少的工作人员使用奇数代码:

select code, count(*)
from workers
where mod(code, 2) = 1
group by code
order by 2
limit 1;

您没有说明您正在使用哪个数据库,因此“仅返回第一行”的语法可能与“LIMIT 1”不同,这是执行此操作的mysql方法。

答案 1 :(得分:1)

这是针对 ORACLE 并解决您的问题。

with newt as
  (  select code, count(*) cnt
     from workers
     where mod(code, 2) = 1
     group by code)
select * 
from newt
where cnt in (select min(cnt) 
              from newt)

答案 2 :(得分:0)

select Code, count(*) MinCount
from Workers
where mod(code, 2) = 1
group by Code
order by MinCount
limit 1

SqlFiddle

请注意,如果有多个代码具有最小计数,则会任意选择其中一个。如果你想要所有这些,那会使事情复杂化,你需要一个子查询的连接。这是查询:

SELECT w.Code, CodeCount
FROM (SELECT Code, count(*) CodeCount
      FROM Workers
      WHERE mod(code, 2) = 1
      GROUP BY Code) w
JOIN (SELECT Code, count(*) MinCount
      FROM Workers
      WHERE mod(code, 2) = 1
      GROUP BY Code
      ORDER BY MinCount
      LIMIT 1) MinQuery
ON CodeCount = MinCount

SqlFiddle

答案 3 :(得分:0)

使用窗口函数并保持所有绑定结果的另一种解决方案。如果您在有关系时不想要很多结果(但只有任意关系),请使用ROW_NUMBER()代替RANK()

SELECT code
FROM
  ( SELECT code 
         , RANK() OVER (ORDER BY COUNT(*)) AS rnk
    FROM workers
    WHERE MOD(code, 2) = 1
    GROUP BY code 
  ) tmp
WHERE rnk = 1 ;

测试(Oracle 11g2): SQL-Fiddle