根据条件在Oracle表中随机记录

时间:2019-05-09 14:40:28

标签: sql oracle

我有一个带有以下列的Oracle表

表结构

Table Structure

在查询中,我需要返回所有CPER> = 40的记录,这是微不足道的。但是,除了CPER> = 40外,我还需要为每个CPID列出5条随机记录。 我附上了记录的样本清单。但是,在我的表格中,我有大约50,000条记录。 感谢您能提供帮助。

3 个答案:

答案 0 :(得分:1)

Oracle解决方案:

with CTE as
(
select t1.*, 
       row_number() over(order by DBMS_RANDOM.VALUE) as rn -- random order assigned
from MyTable t1
where CPID <40
)
select *
from CTE
where rn <=5 -- pick 5 at random

union all
select t2.*, null
from my_table t2
where CPID >= 40

SQL Server:

with CTE as
(
select t1.*, 
       row_number() over(order by newid()) as rn -- random order assigned
from MyTable t1
where CPID <40
)
select *
from CTE
where rn <=5 -- pick 5 at random

union all
select t2.*, null
from my_table t2
where CPID >= 40

答案 1 :(得分:0)

这样的事情怎么样...

SELECT *
FROM   (SELECT CID,
               CVAL,
               CPID,
               CPER,
               Row_number() OVER (partition BY CPID ORDER BY CPID ASC ) AS RN
        FROM   Table) tmp
WHERE  CPER>=40 OR pids <= 5

但是,这不是随机的。

答案 2 :(得分:0)

假设您需要五个其他个随机记录,则可以执行以下操作:

select t.*
from (select t.*,
             row_number() over (partition by cpid,
                                             (case when cper >= 40 then 1 else 2 end)
                                order by dbms_random.value
                               ) as seqnum
      from t
     ) t
where seqnum <= 5 or cper >= 40;

row_number()枚举两组cpid中的行-基于cper值。外部where将获取您想要范围内的所有cper值,并从其他组中获取五个。