【问题标题】:Oracle select random rows from table based on criteria in another table (Stratified Sampling)Oracle 根据另一个表中的条件从表中选择随机行(分层抽样)
【发布时间】:2015-07-28 04:08:28
【问题描述】:

我有 2 张桌子。第一个是其中包含信息的基表,第二个表具有我需要根据表 2 中的标准从表 1 中选择随机行的标准。不希望手动执行此操作,因为我的表中标准的排列很接近到百。需要代码来尝试从我的数据库中获取随机分层样本。

Table_1

   ID          Fruit       Subject 
   123       Apple      Math
   124       Apple      Science  
   125       Apple      History  
   126       Apple      Math  
   127       Apple      Science  
   128       Orange     Math  
   129       Orange     Science  
   130       Orange     Science  
   131       Orange     Science  
   132       Orange     History  
   133       Orange     Science  
   134       Pineapple  History  
   135       Pineapple  History  
   136       Pineapple  History  
   137       Pineapple  History  
   138       Pineapple  Math  

Table_2

   Fruit      Subject   Count
   Apple        Math        1
   Apple        Science     2
   Apple        History     1
   Orange       Science     2
   Orange       History     1
   Pineapple    History     3
   Pineapple    Math        1  

输出(根据表 2 中的标准随机选择)

   ID         Fruit       Subject 
   123      Apple       Math
   124      Apple       Science
   125      Apple       History
   127      Apple       Science
   128      Orange      Math
   129      Orange      Science
   130      Orange      Science
   132      Orange      History
   134      Pineapple   History
   135      Pineapple   History
   137      Pineapple   History
   138      Pineapple   Math

【问题讨论】:

  • 你能详细说明你在说什么标准吗?如果您只需要随机行,则只需加入表并在过滤谓词中应用 ROWNUM,您将获得随机行。
  • 表 2 有条件。因此,取表 2 中的 1st 行,我需要的是表 1 中的 1 个随机样本,其中 Apple 位于 Fruit 中,Math 位于 Subject 中。对于第 2 行,它将是表 2 中的 2 个随机样本,其中 Apple 在 Fruit 中,Science 在 Subject 中。希望这可以澄清。

标签: sql oracle random-sample


【解决方案1】:

听起来你可以使用dbms_random对行进行排序,并使用解析函数row_number在分区内对它们进行排序

select id,
       fruit,
       subject
  from(select t1.*,
              t2.cnt,
              row_number() over (partition by t1.fruit, t1.subject
                                     order by dbms_random.value) rnk
         from table_1 t1
              join table_2 t2
                on( t1.fruit   = t2.fruit and
                    t1.subject = t2.subject ))
 where rnk <= cnt

【讨论】:

  • 太棒了,谢谢贾斯汀!!
猜你喜欢
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多