0

你能给我一个在同一个查询中使用 min 和 count 的例子吗?例如,在这张表上,我想知道具有奇数代码(1 和代码 5)的工人数量较少。

 Table Workers
      Code
       1
       2
       2
       2
       3
       3
       1
       5

谢谢。

4

4 回答 4

1

另一种使用窗口函数并保留所有绑定结果的解决方案。如果在有联系时您不想要很多结果(但只是任意一个),请使用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

于 2012-11-25T11:36:28.847 回答
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)
于 2012-11-24T21:38:08.360 回答
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 的执行方式。

于 2012-11-24T17:57:04.077 回答
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

于 2012-11-24T18:01:56.140 回答