0

我有一个 Oracle 表,我需要从中为给定的一组唯一列组合的每种类型选择给定百分比的记录。

例如,

SELECT distinct column1, column2, Column3 from TableX;

为我提供了该表中唯一记录的所有组合。我需要每个此类组合中每行的百分比。目前我正在使用以下查询来完成此操作,这既冗长又缓慢。

SELECT *  
FROM tableX Sample ( 3 ) 
WHERE Column1 = ‘value1’ and       
      Column2 = ‘value2’ and       
      Column3 = ‘value3 

UNION 

SELECT *  
FROM tableX Sample ( 3 ) 
WHERE Column1 = ‘value1’ and       
Column2 = ‘value2’ and       
Column3 = ‘value4 

UNION  
 …   
 …  
SELECT *  
FROM tableX Sample ( 3 ) 
WHERE Column1 = ‘valueP’ and       
Column2 = ‘valueQ’ and       
Column3 = ‘valueR’  

“值”中的后缀组合对于该表是唯一的(从第一个查询中获得)

如何提高查询的长度和速度?

4

1 回答 1

2

这是一种方法:

select t.*
from (select t.*,
             row_number() over (partition by column1, column2, column3 order by dbms_random()
                               ) as seqnum,
             count(*) over (partition by column1, column2, column3) as totcnt
      from tablex t
     ) t
where seqnum / totcnt <= 0.10 -- or whatever your threshold is

它用于row_number()以随机顺序为每个组中的行分配一个序号。该where子句选择您想要的比例。

于 2013-02-20T16:52:24.393 回答