选择count()max()日期

时间:2010-04-26 20:30:57

标签: sql oracle oracle-xe

我有一张包含轮班历史的表格以及emp id。

我正在使用此查询通过指定要计算的范围来检索员工列表及其总班次:

SELECT ope_id, count(ope_id)
FROM operator_shift
WHERE ope_shift_date >=to_date( '01-MAR-10','dd-mon-yy') and ope_shift_date
<= to_date('31-MAR-10','dd-mon-yy')
GROUP BY OPE_ID 

给出了

   OPE_ID      COUNT(OPE_ID)
     1            14
     2             7
     3             6
     4             6
     5             2
     6             5
     7             2
     8             1
     9             2
    10             4

选择了10行。

如何选择在指定范围日期内班次最多的员工?

3 个答案:

答案 0 :(得分:1)

假设您的Oracle版本足以支持公用表表达式:

With ShiftCounts As
    (
    SELECT ope_id, count(ope_id) ShiftCount
        , ROW_NUMBER() OVER( ORDER BY Count(ope_id) Desc ) ShiftRank
    FROM operator_shift
    WHERE ope_shift_date >=to_date( '01-MAR-10','dd-mon-yy') 
        and ope_shift_date <= to_date('31-MAR-10','dd-mon-yy')
    GROUP BY OPE_ID 
    )
Select ope_id, ShiftCount
From ShiftCounts
Where ShiftRank = 1

答案 1 :(得分:0)

这样的事情可能是:

SELECT TOP 1 ope_id, Count(ope_id)
FROM operator_shift
WHERE ope_shift_date >=to_date( '01-MAR-10','dd-mon-yy') and ope_shift_date
<= to_date('31-MAR-10','dd-mon-yy')
GROUP BY OPE_ID 
ORDER BY Count(ope_id) DESC

答案 2 :(得分:0)

使用:

SELECT t.ope_id,
       t.num
  FROM (SELECT os.ope_id, 
               COUNT(os.ope_id) AS num
          FROM OPERATOR_SHIFT os
         WHERE os.ope_shift_date BETWEEN TO_DATE('01-MAR-10','dd-mon-yy') 
                                     AND TO_DATE('31-MAR-10','dd-mon-yy')
      GROUP BY os.ope_id
      ORDER BY num DESC) t
 WHERE ROWNUM = 1

参考: