Select a fixed number of random rows

Hi,
I just would like to select a fixed number of random rows from a table. That is, I would like to get 5 rows, without specifying the row_id, and the selected rows should "always" be different. Just as picking 5 balls out of a big box (which is filled with many balls).
Is there a way to easily put it into one sql statement or do I have to write a workaround in the programming language I use?
Thanks a lot in advance,
CQ

AskTom has a discussion on this:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:6075151195522
Note that it requires that you
1) Generate a random number for every row in the table
2) Sort the table by those random numbers
which is a significant performance hit if the table is large.
Justin

Similar Messages

  • Fixed number of detail rows

    Hi all,
    I have "shipment form" that I need to replicate in reporting services - see image.
    FYI, there is more header info below the "shipment details" section...
    My issue, is fixing the number of detail lines, my data can have between 1 and 5 detail lines & I would like to use a table rather than lists / textboxes etc.
    Is there any way I can fix the detail lines lines to 5 i.e. i need the shipment detail section to be the same size - regardless of the number of rows.
    I think one solution is do it in the query (return empty detail columns when they don't exist) - but I'm guessing there is a correct way to do it in the report.
    Any assistance greatly appreciated.
    Thanks in advance.

    Hi Clay,
    I am not sure if it's the cleanest option, but it works :-)
    In the query of the shipment details, add the following (assuming your query has just five output columns):
    UNION ALL
    SELECT '', '', '', '', ''
    UNION ALL
    SELECT '', '', '', '', ''
    UNION ALL
    SELECT '', '', '', '', ''
    UNION ALL
    SELECT '', '', '', '', ''
    ORDER BY ColumnName DESC
    This will add blank lines to your query. Now you have to tell the tablix that it should not display more than 5 rows. Right-click on the details icon on the left of the details row and select "Row visibility". Select the option "Show or hide based on an
    expression" and type the following in the expression box:
    =Iif(RowNumber(Nothing) <= 5, False, True)
    The added blank lines and this visibility expression should always create 5 rows.
    Hope this helps!
    - If a post answers your question, please click "Mark As Answer" on that post!

  • How to Efficiently Sample a Fixed Number of Rows

    Good afternoon. I need to select a specific number of random rows from a table, and while I believe my logic is right it's taking too long, 30 minutes for a routine data size. Hopefully someone here can show me a more efficient query. I've seen the SAMPLE function, but it just randomly selects rows on a one-by-one basis, without a guaranteed total count.
    This is the idea:
    INSERT INTO Tmp_Table (Value, Sequence) SELECT Value FROM Perm_Table, DBMS_RANDOM.VALUE;
    SELECT Value FROM Tmp_Table WHERE ROWNUM <= 1234 ORDER BY Sequence;I'd need to put the ORDER BY in a subselect for ROWNUM to work correctly, but anyway that's just an illustration. My actual need is a little more complicated. I have many sets of data; each set has many rows; and for each set I need to return a specific (different) number of rows. Perhaps project A has three rows in this table, and I want to keep two of them; project B has two rows, and I want to keep one of them. So I need to identify, for each row, whether it's valid for that project. This is what my data looks like:
    Project Person  Sequence Position Keeper
    A       Bill    1234     1        Yes
    A       Fred    5678     3        No
    A       George  1927     2        Yes
    B       April   5784     2        No
    B       Janice  2691     1        YesI populate Sequence with random values, then calculate the position of each person within their project, and finally discard people who's Position is greater than Max_Targets for the Project. Fred and April have the highest random numbers, so they're cut. It's not the case that I'm just trimming one person from each project; the actual percentage kept will range from zero to 100.
    Populating the list with random values is not time-consuming, but calculating Position is. This is my code:
    UPDATE Tmp_Targets T1
    SET Position =
      SELECT
       COUNT(*)
      FROM
       Perm_Targets PT1
       INNER JOIN Perm_Targets PT2 ON PT1.Project = PT2.Project
       INNER JOIN Tmp_Targets T2 ON PT2.Target = T2.Target
      WHERE
           T1.Target = PT1.Target
       AND T2.Sequence <= T1.Sequence
      );The Target fields are PKs, and the Project and Sequence fields are indexed. Is there a better way to approach this? I could write a cursor that pulls out project codes and performs the above operations for each project in turn; that would be logically simpler and possibly faster. Has anyone here addressed a similar problem before? I'd appreciate any ideas.
    This is on 9.2, in case it matters. Thank you,
    Jonathan

    You've not given any indication of how max targets for a given project is determined, so for my example I'm using the ceiling of 1/2 of the number of records in each project which gives the same number of yes and no responses per project as you had:
    with dta as (
      select 'A' project, 'Bill' person from dual union all
      select 'A', 'Fred' from dual union all
      select 'A', 'George' from dual union all
      select 'B', 'April' from dual union all
      select 'B', 'Janice' from dual
    ), t1 as (
      select project
           , person
           , row_number() over (partition by project order by dbms_random.value) ord
           , count(*) over (partition by project) cnt
           , rownum rn
        from dta
    select project
         , person
         , ord
         , cnt
         , case when ord <= ceil(cnt/2) then 'Yes' else 'No' end keep
      from t1
      order by rn
    PROJECT PERSON ORD                    CNT                    KEEP
    A       Bill   2                      3                      Yes 
    A       Fred   3                      3                      No  
    A       George 1                      3                      Yes 
    B       April  1                      2                      Yes 
    B       Janice 2                      2                      No  
    5 rows selectedIn this example I use an analytic function to assign a random ordering for each record within a project in the middle query, in the final output query I am determining the yes no status based on the order within a project and the count of records in the project. If you had a table of projects indicating the thresh hold you could join to that and use the thresh hold in place of the ceil(cnt/2) portion of my inequality in the case statement.

  • How to select a random row with for update?

    Hi,
    I have a package that needs to assign a random, reusable number (ID) that is not currently being used - to a procedure.
    I'm trying to simulate a pool of numbers (IDs) using a table that has an ID and IS_USED columns.
    How do I do:
    select a random ID (random row)
    from pool_table
    where IS_USED is 0 (not taken)
    FOR UPDATEThe for update is to lock the row from being taken by another process calling the package.
    OR:
    Can I simulate a pool of numbers with a different object (not a table)?
    I need the numbers to be coherent between sessions (thus package variables will not work) and only one session uses the same ID at any given time. When it finishes the number becomes available for further runs.
    Thanks.
    Edited by: Pyrocks on Nov 7, 2010 10:45 AM

    This works on Oracle 11g (probably on 10g too, but I haven't tested):
    CREATE OR REPLACE PACKAGE REUSABLE_RANDOM_NUMBERS
    IS
      FUNCTION GET_NUMBER RETURN NUMBER;
    END REUSABLE_RANDOM_NUMBERS;
    create or replace
    PACKAGE BODY REUSABLE_RANDOM_NUMBERS
    IS
      TYPE NUM_TABLE_TYPE IS TABLE OF CHAR INDEX BY PLS_INTEGER;
      MIN_VALUE CONSTANT PLS_INTEGER := 0;
      max_value CONSTANT PLS_INTEGER := 10;
      NUM_TABLE NUM_TABLE_TYPE;
      FUNCTION GET_NUMBER RETURN NUMBER
      IS
        num PLS_INTEGER;
      BEGIN
        FOR I IN 1 .. 100 LOOP
           NUM := DBMS_RANDOM.VALUE( min_value, max_value );
           IF NOT NUM_TABLE.EXISTS( NUM ) THEN
              NUM_TABLE( NUM ) := 'X';
              RETURN NUM;
           END IF;
        END LOOP;
        FOR I IN MIN_VALUE .. MAX_VALUE LOOP
          IF NOT NUM_TABLE.EXISTS( i ) THEN
              NUM_TABLE( i ) := 'X';
              RETURN i;
           END IF;
        END LOOP;
        RAISE_APPLICATION_ERROR( -20991, 'All possible values have ben used, cannot assign a new one' );
      END;
    END REUSABLE_RANDOM_NUMBERS;
    SELECT REUSABLE_RANDOM_NUMBERS.GET_NUMBER
    FROM DUAL
    connect by level <= 11;
    GET_NUMBER            
    3                     
    4                     
    6                     
    2                     
    1                     
    7                     
    8                     
    0                     
    9                     
    5                     
    10                    
    11 rows selected
    SELECT REUSABLE_RANDOM_NUMBERS.GET_NUMBER
    FROM DUAL;
    Error starting at line 44 in command:
    SELECT REUSABLE_RANDOM_NUMBERS.GET_NUMBER
    FROM DUAL
    Error report:
    SQL Error: ORA-20991: All possible values have ben used, cannot assign a new one
    ORA-06512: przy "TEST.REUSABLE_RANDOM_NUMBERS", linia 26

  • Fixed number of rows

    hi,
    all.
    i wnt to dispaly only fixed no of row in output but there  mayee to more record in internal table .how can i do that
    suppose i want to dispaly only 10 record in output but there maye be more that 10 record in inetrnal table,we will
    not fixe in selection query,how we will do that.

    Hi,
    Use a counter and move the fixed number of records to another internal table and display it.
    loop at itab.
    count = count + 1.
    move-corresponding itab to itab1.
    append itab1.
    if count > 10.
    exit.
    endif.
    endloop.
    Now use itab1 to display the output.
    Regards,
    Vikranth

  • How to efficiently select random rows from a large table ?

    Hello,
    The following code will select 5 rows out of a random set of rows from the emp (employee) table
    select *
      from (
           select ename, job
             from emp
           order by dbms_random.value()
    where rownum <= 5my concern is that the inner select will cause a table scan in order to assign a random value to each row. This code when used against a large table can be a performance problem.
    Is there an efficient way of selecting random rows from a table without having to do a table scan ? (I am new to Oracle, therefore it is possible that I am missing a very simple way to perform this task.)
    thank you for your help,
    John.
    Edited by: 440bx on Jul 10, 2010 6:18 PM

    Have a look at the SAMPLE clause of the select statement. The number in parenthesis is a percentage of the table.
    SQL> create table t as select * from dba_objects;
    Table created.
    SQL> explain plan for select * from t sample (1);
    Explained.
    SQL> @xp
    PLAN_TABLE_OUTPUT
    Plan hash value: 2767392432
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |   725 | 70325 |   289   (1)| 00:00:04 |
    |   1 |  TABLE ACCESS SAMPLE| T    |   725 | 70325 |   289   (1)| 00:00:04 |
    8 rows selected.

  • Create spreadsheet file with a fixed number of rows

    What is the most straight forward way to create a series of spreadsheet files each with a new file name and fixed number of rows.  We have a data acquisition process that creates a new 1D array every 2 seconds.  We'd like to build a series of spreadsheet files each having two hours or 3600 rows of data.  Is there a best way to do this in LV9?
    john

    Use the low-level FileI/O Vis with Write to Text File.vi where you open a new file with every N iteration like this:
    You just have to convert your 1D Array to string before.
    If you would like to have a new file every N hours you should create a FGV which checks the elapsed time using Get Date/Time in Seconds.vi, which is more appropriate for longtime applications.
    Christian

  • Selecting a small number of rows

    Hello,
    I am looking for something in PL/SQL that will allow me to return a limited number of rows. In other SQL's this might be something like:
    set row count=100
    select * from tab1 --- returns first 100 rows found

    SQL> select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7566 JONES      MANAGER         7839 02-APR-81       2975       1000         20
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    10
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7788 SCOTT      ANALYST         7566 09-DEC-82       3000                    20
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7876 ADAMS      CLERK           7788 12-JAN-83       1100                    20
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    10
    14 rows selected.
    SQL> select e.empno, e.ename, e.job, e.hiredate
      2    from (select rownum rn, empno, ename, job, hiredate
      3            from emp) e
      4   where e.rn <= 10;
         EMPNO ENAME      JOB       HIREDATE
          7566 JONES      MANAGER   02-APR-81
          7902 FORD       ANALYST   03-DEC-81
          7839 KING       PRESIDENT 17-NOV-81
          7698 BLAKE      MANAGER   01-MAY-81
          7782 CLARK      MANAGER   09-JUN-81
          7369 SMITH      CLERK     17-DEC-80
          7499 ALLEN      SALESMAN  20-FEB-81
          7521 WARD       SALESMAN  22-FEB-81
          7654 MARTIN     SALESMAN  28-SEP-81
          7788 SCOTT      ANALYST   09-DEC-82
    10 rows selected.
    SQL>

  • How to show  a fixed number of rows in JTable

    Hi,
    I have to show only a fixed number of rows in the table .
    After scrolling number of rows must not be changed.

    I don't understand the question.
    The number of visible rows is dependent on the size of the scroll pane.
    Scrolling does not change the number of rows that are visible.

  • How to display a fixed number of rows in a page when using CL_GUI_ALV_GRID

    Hy experts
    How to display a fixed number of rows in a page when using CL_GUI_ALV_GRID?? lets say 500 ?? because my display table it may contain in some cases 10.000 and evidently I can t see all of them..
    I have a button in my toolbar witch triggers this event
    (display 500 records ) but I don t have the logic to do this only with methods of CL_GUI_ALV_GRID.
    can you tell me a standard method of CL_GUI_ALV_GRID witch can help me do this?? any hint will be good..
    Till now I was used to add a column to my structure witch represents a flag that is a number corresponding to every 500 records (a batch containing 500 records )
    first       500 - flag -> 1
    second  500 - flag -> 2
    etc..but I m convinced that exists a way of doing this more easy..without damaging my structure..
    thanx in advance..don t be shy..reply if you have any hints..

    Hi,
    if method SET_FILTER_CRITERIA doesn´t help, I think that you must work with 2 internal tables, a counter and a loop for filtering the records to be displayed:
    case counter.
      when 1.
         loop at int_table1 from 1 to 500.      "<-- your table with all records
           move int_table1 to int_table2
        endloop.
      when 2.
         loop at int_table1 from 501 to 1000.     
           move int_table1 to int_table2
        endloop.
    etc, etc.
    Call grid-->SET_TABLE_FOR_FIRST_DISPLAY
       exporting
         IT_OUTTAB = int_table2                "<-- instead of your currently table int_table1

  • Fixed number of rows in ADF table

    Can we specify fixed number of rows for ADF table so even no rows displayed it will still show 10 empty rows.

    the rangesize property determines how many rows will be displayed and controls paging. If there are no rows to begin with (if I understand the question correctly) rangesize won't have any effect.

  • Select Random Rows in PL/SQL

    I would like to know if anyone has a suggestion fora select statement that would select random rows from a table based on the following:
    The table contains 1-to-many categories. From each of these categories I need to select a 'x' amount of rows based upon the category id, with a total of 25 rows being selected overall. Some categories will have only 1 row selected, some will have more than 1. The rows selected contain questions that are either multiple choice (type=1) or true/false (type=2). The total rows selected (25) cannot contain more than 20% of true/false questions. Anyone have a solution for a select statement? Thanks.

    Not having a database at hand. To be treated as a template
    with
    parameters as
    (select all_rows,
            all_categories,
            :all_questions all_questions,                               -- your 25
            :category_questions category_questions,                     -- your 'x'
            ceil(all_categories / :category_questions) pick_categories,
            :type_2_percentage type_2_percentage                        -- your 20% expressed as 0.2
       from (select count(*) all_rows,
                    count(distinct category) all_categories,
               from your_table
    categories_scrambled as
    (select category,dense_rank() over (order by categories_mix) category_choice
       from (select category,
                    ceil(dbms_random.value(0,1000)) categories_mix
               from your_table
              group by category
    rows_scrambled as
    (select category,question_type,question_text,dense_rank() over (order by rows_mix) row_choice
       from (select category,question_type,question_text,
                    ceil(dbms_random.value(0,10000)) rows_mix
               from your_table
    combination as
    (select r.category,r.question_type,r.question_text,r.row_choice,c.category_choice,
            row_number() over (partition by r.row_choice,r.question_type order by r.row_choice) row_mark
       from rows_scrambled r,categories_scrambled c
      where r.category = c.category
    type_2_questions as
    (select question_text,question_type,category
       from combination
      where category_choice <= (select pick_categories from parameters)
        and row_mark <= floor(:all_questions * :type_2_percentage / (select pick_categories from parameters))
        and question_type = 2
    type_1_questions as
    (select question_text,question_type,category,row_number() over () the_count
       from combination
      where category_choice <= (select pick_categories from parameters)
        and row_mark <= ceil((:all_questions - (select count(*) from type_2_questions)) / (select pick_categories from parameters))
        and question_type = 1
    select question_text,question_type,category
      from type_2_questions
    union all
    select question_text,question_type,category
      from type_1_questions
    where the_count <= :all_questions - (select count(*) from type_2_questions)Regards
    Etbin

  • Know the number of the row in a select

    Hi experts,
    I´m doing a select * ... such as:
    *      SELECT *
    *        FROM YPLM00 CLIENT SPECIFIED
    *        WHERE mandt = sy-mandt
    *        AND TIPOL = 'RS'
    *        AND PSPNR = yplm00_tree-pspnr
    *        AND TIPOP = yplm00_tree-tipop
    *        AND PROCE = yplm00_tree-proce
    *        AND ID_ED = yplm00_tree-id_ed
    *        AND TIPOE = yplm00_tree-tipoe
    *        AND ID_EN = yplm00_tree-id_en.
    Can i know the number of the row that is affected? I don´t want the total of rows... i want the number of each one...
    Thanks in advance,
    regards

    >
    Victor Capi wrote:
    > I have a table with
    >
    > Q   W   E   R
    > E   T    U    I
    > A   Q    E    T
    > A   W   R    F
    Hi Victor,
    I see what you mean.  The problem is still that there isn't actually a row number associated with each database row.  In your example, what is the primary key of the table?  If it is say A Q E for row 3 and A W R for row 4 then that is the only way you can identify them.
    It sounds like you have performance considerations so probably change the SELECT * to only SELECT the fields you need.  Also change it so that you are SELECTing into a table - so in your example you would get both rows 3 and 4.  Then if you want to process those rows, you will have to use their primary keys to identify them, say by LOOPing through the internal table you have just selected them into.
    Do you already have an internal table with values you wish to read from this table?  So say you have a table with 500 entries which all define the value in the first column of this table?  If so you could try chaning to using a FOR ALL ENTRIES in your select to get all rows for the table in one hit - you can then process them again in a LOOP.
    Hope this helps in some way.
    Gareth.

  • How to display fixed number of rows on rtf file

    Hi everyone,
    I have the following requirement. The pdf output should have fixed number of 33 lines in a group by. The rows in group by can vary for each group . For eg: If a group has 3 rows , the pdf output should print 3 lines and 30 empty lines, and if group has 2 lines, the out put should print 31 emty lines.
    can anyone please help me with this requirement?
    Thanks
    Sunny

    Take a look at this blog post: http://blogs.oracle.com/xmlpublisher/entry/anatomy_of_a_template_i_fixed
    Thanks,
    Bipuser

  • How to know Number of the Row which is selected in Advanced table

    Hi All
    I have a requirement where in an advanced table, when user clicks on copy icon against a row..a new row is created with copied values of the row against which copy action is performed.My issue is: assume in table i have got 5 rows..when user clicks on copy..my copied row gets created in the end..but i want tht row to be created directly under the row against which copy action is performed.I think somehow if i am able to know the position number of the row against which copy action is performed..i should be able to achieve it...can you please help me on this.
    Thanks
    Raj

    hi raj,
    create a fire action to the copy image.
    and then copy this method in to u r AM,
    public void copy action(String s)
    PwrPosViewShipmentsVOImpl sVO = getPwrPosViewShipmentsVO();
    RowSetIterator rowsetiterator;
    OADBTransaction oadbtransaction;
         rowsetiterator = sVO.findRowSetIterator("ships");
    int i;
         int j;
    if(rowsetiterator == null)
    rowsetiterator = sVO.createRowSetIterator("ships");
    oadbtransaction = getOADBTransaction();
    rowsetiterator.reset();
    i = 0;
    if(!sVO.isPreparedForExecution())
    rowsetiterator.setRowValidation(false);
    String s1;
    PwrPosViewShipmentsVORowImpl sVORowImpl1;
    PwrPosViewShipmentsVORowImpl sVORowImpl=null;
    do
    if(!rowsetiterator.hasNext() || i >= sVO.getFetchedRowCount())
    break;
    i++;
    sVORowImpl = (PwrPosViewShipmentsVORowImpl)rowsetiterator.next();
    s1 = copyServerUtil.replaceNull(sVORowImpl.getAttribute("view attribute of the referenced column"));
    } while(!s.equals(s1));
    j = sVO.getRangeIndexOf(sVORowImpl);
    sVORowImpl1 = (PwrPosViewShipmentsVORowImpl)rowsetiterator.createRow();
    sVO.insertRowAtRangeIndex(j + 1, sVORowImpl1);
    rowsetiterator.closeRowSetIterator();
    * create a new class file under the server folder and paste the below into that. and then import that class file into u r AM. and then try to run as a whole. u will get ur required work.
         public static final String replaceNull(Object obj)
    if(obj == null || obj.equals("null"))
    return "";
    } else
    return obj.toString();
    }

Maybe you are looking for

  • How can i remove a name that comes up as the Home user next to the House symbol?

    For some reason when the House symbol appears in any incidence on my Mac Pro lap top although it is only me that has ever used it it shows the name Sharon next to the house which isn't mine! I can only presume it has been imported across with other s

  • DVD burn error message

    I get this error message when I try to burn a data DVD: "Burning the disk failed because communication to the disk drive failed. (error code 0 x 80020022) I am attempting to use the original drive system (Pioneer DVD-RW DVR 104) and it plays CD's and

  • Can't print with airport usb connection only

    i have spent the last 3 days searching for help to fix my problem - PLEASE HELP!!! using: imac osx 10.6.8 canon image class mf8350cdn airport extreme base station I cannot seem to print wirelessly with my imac using just the USB connection on the air

  • App shown in "Purchase History" but not shown in "Purchase" tab

    I tried syncing my Ipad2 to Ipad3. Only some of my  apps transferred to the new Ipad3. I checked Itunes purchase log "Purchase History"  and it DOES show that I purchased the apps, but yet the app is not shown on the ipad3. On the ipad3, went into Ap

  • 'Format Payment Instructions with Text Output' program ending in error

    Hi All, 'Format Payment Instructions with Text Output' program of the payment cycle is completing in to error. error is: length of the output - baos::4914 After formatting, periodicSeq is null or empty.{} length of the output - baos::4914 Exit: iby.s