为什么min函数返回多行

时间:2018-10-08 12:32:17

标签: sql oracle oracle11g

我有一个要求来计算我们向员工提供的所有第一个报价的数量,我们扩展了多少个报价无关紧要,就是捕获第一个报价。我写了这段代码来捕获该代码,但是如果我们扩展了一个以上的报价,那么它就会计数两次。关于我需要调整我的代码以仅计数一次的任何建议,无论有多少提议已过期?

(SELECT /*+ materialize */ 1 
FROM
(
  SELECT /*+ materialize */ 1, Rank() OVER(PARTITION BY EMP_NUM  order by CREATION_DT   asc) AS RECNUM
  FROM CTE_OFFERS ACP
  WHERE STS_NAME = 'Extended'
  AND  STEP_NAME = 'Offer'
  AND ACP.EMP_NUM  = EXT.EMP_NUM  
  AND ACP.TITLE = EXT.TITLE
 ) T2
    WHERE RECNUM=1
)  AS t1,

2 个答案:

答案 0 :(得分:1)

使用row_number()函数,删除PARTITION BY EMP_NUM并考虑以下事项:

select * 
  from
  (
   with cte_offers( emp_num, creation_dt ) as
   (
    select 17, trunc(sysdate)   from dual union all
    select 18, trunc(sysdate)   from dual union all
    select 19, trunc(sysdate)+1 from dual     
   )
   select emp_num, row_number() over (order by creation_dt asc) as recnum
     from cte_offers
   )
 where recnum = 1
 order by emp_num;

EMP_NUM RECNUM
------- ------
  17       1

即使两个CREATION_DT的值相同,也会产生不同的数字(recnum)。

Rextester Demo

答案 1 :(得分:0)

假设,只有一个“第一”要约扩展到任何员工, 要扩展所有首批报价,您需要做的是获得有扩展报价的不同员工人数:

select count(distinct emp_num)
from cte_offers
where sts_name = 'Extended'
and step_name = 'Offer';

如果您需要将首次报价的数量扩展到一个员工(即给定emp_num),则根据上述假设可以为0或1:

select count(*)
from dual
where exists (
    select 1
    from cte_offers
    where sts_name = 'Extended'
    and step_name = 'Offer'
    and emp_num = ?
)