我有一个带有以下列的Oracle表
表结构
在查询中,我需要返回所有CPER> = 40的记录,这是微不足道的。但是,除了CPER> = 40外,我还需要为每个CPID列出5条随机记录。 我附上了记录的样本清单。但是,在我的表格中,我有大约50,000条记录。 感谢您能提供帮助。
答案 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
值,并从其他组中获取五个。