每天表中可能插入很多数据,想取出每天数据总量的一部分数据出来,这样的SQL如何写?
假设:
 create table TEMP
(
  PK   VARCHAR2(10),  --Primary Key
  COL1 VARCHAR2(8),
  COL2 DATE
)
数据:
  PK1      COL1      COL2
  001      AC         2004-11-10
  002      TT        2004-11-10
  003     O          2004-11-10
  004     A          2004-11-10 
..................................................    --这里省略2004-11-10输入的数据
  025    WE            2004-11-11
  026   QQ             2004-11-11
  ..................................................  --这里省略2004-11-11输入的数据现假设2004-11-10中有24条数据,2004-11-11中有150条数据,如何根据COL2即根据日期求出每天数据量的10%的数据出来?即结果2004-11-10中应该会查出2条数据,2004-11-11中查出15条数据.
最好能一条select语句搞定。谢谢各路高手。

解决方案 »

  1.   

    select * from table t where rownum<=(select count(*)/10 from table a t.col2=a.col2)
      

  2.   

    select * from table t where to_char(t.col2)='2004-11-11' rownum<=(select count(*)/10 from table a t.col2=a.col2)
    union all
    select * from table t where to_char(t.col2)='2004-11-10' rownum<=(select count(*)/10 from table a t.col2=a.col2)
      

  3.   

    SELECT * FROM (
      SELECT col2,col1,ROW_NUMBER()
      OVER (
        PARTITION BY to_char(col2,'yyyy-mm-dd') ORDER BY col2
      ) ratio FROM temp
    ) a
    WHERE a.ratio <= (select round(count(*)*0.5) tatio from temp b
    where to_char(a.col2,'yyyy-mm-dd')=to_char(b.col2,'yyyy-mm-dd')
    group by to_char(b.col2,'yyyy-mm-dd'))
    /
      

  4.   

    上面的是取50%的记录,现在改成10%SELECT * FROM (
      SELECT col2,col1,ROW_NUMBER()
      OVER (
        PARTITION BY to_char(col2,'yyyy-mm-dd') ORDER BY col2
      ) ratio FROM temp
    ) a
    WHERE a.ratio <= (select round(count(*)*0.1) tatio from temp b
    where to_char(a.col2,'yyyy-mm-dd')=to_char(b.col2,'yyyy-mm-dd')
    group by to_char(b.col2,'yyyy-mm-dd'))
    /
      

  5.   

    由于表里面的数据非常多,涉及到很多年的数据,用union all效率不是太好!
      

  6.   

    刚刚上面是按照一定的顺序,对不同的时期分别取10%的记录
    下面的语句可以随机按你设定的比例取记录,每次取的记录不同,但都是10%
    比例你可以自己改改,比如要20%,知道在哪里改吧?把round(count(*)*0.1)改成round(count(*)*0.2)
    就是分别取20%记录。根据你的假设,会分别取出5条记录和30条记录
    因为24的20%是4.8,四舍五入就是5了,你也可以改改语句,取出4条也可以的,不要四舍五入即可SELECT * FROM (
      SELECT col2,col1,ROW_NUMBER()
      OVER (
        PARTITION BY to_char(col2,'yyyy-mm-dd') order by trunc(dbms_random.value(0,10))
      ) ratio FROM temp
    ) a
    WHERE a.ratio <= (select round(count(*)*0.1) ratio from temp b
    where to_char(a.col2,'yyyy-mm-dd')=to_char(b.col2,'yyyy-mm-dd')
    group by to_char(b.col2,'yyyy-mm-dd'))
    /
      

  7.   

    感谢 ATGC(这一生受了很多委屈吃了很多苦。。) 和liuyi8903(西西) .
      ATGC的方法能实现,只是再实现处理一下四舍五入的问题,因为如果某天的记录非常少的话,就没有记录select 出来.