一个表2列,以a列为基准,a列的每个值,随机取出b列的一个值,怎么做?详见帖子比如 表 table 如下 a      b张三    20
张三    70
李四    49
李四    90
王五    77
王五    44从上表数规则:以a列为基准,一个a列的值 随机取出 b列的一个值,例如 张三 有2行,那么 随机取一个b列值得到下面:a         b
张三      20
李四      49
王五      44请问怎么做?

解决方案 »

  1.   

    with tt as(
      select '张三' a,20 b from dual
      union all select '张三',70 from dual
      union all select '李四',49 from dual
      union all select '李四',90 from dual
      union all select '王五',77 from dual
      union all select '王五',44 from dual)
     
    select a,
           substr(b_concat,
                  instr(',' || b_concat, ',', 1, rd),
                  instr(b_concat || ',', ',', 1, rd) -
                  instr(',' || b_concat, ',', 1, rd)) b
      from (select a,
                   wm_concat(b) b_concat,
                   round(dbms_random.value(1, count(1))) rd
              from tt
             group by a);
      

  2.   

    with tt as(
      select '张三' a,20 b from dual
      union all select '张三',70 from dual
      union all select '李四',49 from dual
      union all select '李四',90 from dual
      union all select '王五',77 from dual
      union all select '王五',44 from dual)select a,b from(
      select tt.*,
        row_number()over(partition by a order by dbms_random.value)rn 
      from tt
    )where rn=1;