How to select rows randomly by the percentage of lines by specific column

I need to select exactly 20% of lines by Department randomly. Ex, table composed of 50 records for the Sales Department, 60 discs for the Department of human resources. I need to get 10 records of the Department sales and 12 records of Department of human resources. but records should be chosen at random. How to get out of it? Thanks in advance.

Select

DEPTNO

count (*) NTC

WCP

Deptno group

DEPTNO CNT

30 6

20 5

3 of 10

Choose 50% in every department at random

expected (round up to the next integer)

DEPTNO CNT

30 3

20 3

2 of 10

Select * from)

Select

EmpNo

deptno

, count (*) during the (partition deptno) cnt

row_number() over (partition by deptno arrested by dbms_random.random) rn

WCP

)

where rn<=>

order by deptno

EMPNO DEPTNO CNT RN

7782 10 3 1

7934 10 3 2

7566 20 5 1

7876 20 5 2

7902 20 5 3

7900 30 6 1

7521 30 6 2

7654 30 6 3

Tags: Database

Similar Questions

  • How effectively select rows randomly a large table?

    Hello

    The following code selects 5 lines of a random set of rows in the table emp (employee)
    select * 
      from (
           select ename, job
             from emp
           order by dbms_random.value()
            )
    where rownum <= 5
    My concern is that the internal selection causes a table scan in order to assign a random value to each line. This code when it is used against a large table can be a performance issue.

    Is there an effective way to random selection rows in a table without having to do a table scan? (I'm new to Oracle, so it is possible that miss me a very simple way to perform this task.)

    Thank you for your help,

    John.

    Published by: 440bx on July 10, 2010 18:18

    Take a look at the clause of the select statement. The number in brackets 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.
    
  • How to select multiple cells at the same time?

    Hello

    How to select multiple cells at the same time? What is the keyboard shortcut?

    Thank you to.

    Flo, a french guy.

    Hold down the CMD key when you select the cells.

  • How to select multiple messages in the messaging application in Windows RT?

    How to select multiple messages in the messaging application in Windows RT?

    For contact:

    1) press the first mail

    (2) then drag the 2nd mail left or right a little bit.

    Repeat 2) for all other mails you want to select. You can use the same way to deselect.

    For the mouse:

    Use the ctrl and shift keys, like the Windows desktop version

    I don't know if there is a way to make the selection of the beach of 'shift' by touch only.

  • How can I change my code the method to set a specific line id in my lov as a default?

    Mr President.

    How can I change my code the method to set a specific line id in my lov as a default value instead of the first value?

        public String defaultDebit() {
    
    
           String debit = (String)getAttributeInternal(DEBIT);
           if (debit == null) {
              COAViewRowImpl coaRow = (COAViewRowImpl)getDebitView1().first();
              if (coaRow != null) {
                 debit = coaRow.getAcctId();
              }
           }
           return debit;
        }
    

    Concerning

    You can see the below example code. This code assumes a view attribute named AcctName and the code returns the AcctId when the AcctName is DEFAULT_DEBIT.

    public String defaultDebit() {}

    String output = (String) getAttributeInternal (DEBIT);
    If (flow == null) {}
    getDebitView1 (.reset ());
    While (getDebitView1 () .hasNext ()) {}
    COAViewRowImpl coaRow = (COAViewRowImpl) getDebitView1 () .next ();
    If (coaRow! = null) {}
    If (coaRow.getAcctName () .equals ("DEFAULT_DEBIT"))
    flow = coaRow.getAcctId ();
    }
    }
    }
    return flow;
    }

    Let us know if this does not work in your case.

    Thank you

  • How to select a random line with update?

    Hello

    I have a package to assign a number at random and reusable (ID) that is not currently in use - a procedure.
    I'm trying to simulate a set of numbers (IDs) using a table that has a column ID and IS_USED.

    How to:
    select a random ID (random row) 
    from pool_table
    where IS_USED is 0 (not taken)
    FOR UPDATE
    The update is to lock the line to be picked up by another process calling the package.

    GOLD:

    I can simulate a set of numbers with another object (not a table)?
    I need the numbers to be consistent between sessions (as well as package variables do not work) and only a single session using the same code at any time. When it finishes the number becomes available to the other races.

    Thank you.

    Published by: Pyrocks on November 7, 2010 10:45

    I completely forgot to SKIP LOCKED. You need not a sequence. Try:

    declare
        cursor pool_cur
          is
            select  *
              from  (
                     select  *
                       from  pool_tbl
                       order by round(dbms_random.value(1,cycle_value))
                    )
              for update
              skip locked;
        id_to_use number;
    begin
        while id_to_use is null loop
          for rec in pool_cur loop
            id_to_use := rec.id;
            exit;
          end loop;
        end loop;
    end;
    /
    

    SY.

  • How to select rows whose column contains specific characters?

    It is a telling of the T1 table with say column C1

    Either the C1 field values:

    1st row) OF/SPT/A/FWD
    line 2) G/SPT/DE/OF/SPT
    rank 3) R/FWD/SPT/A/FWD/FWD
    rank 4) A/A/OF/SPT/FWD
    rank 5) FWD/SPT/E/OF/A


    How to get only the lines whose C1 column contains FWD last?

    We can solve this problem with the simple use of a wildcard character:

        select *
        from t1
        where c1 like '%FWD'
        /
    

    Note that this query runs a full table scan, because any index you can have on C1 will be ignored: the indexes are organized on the main characters.

    Cheers, APC

  • How to select a part of the message under macOS Sierra?

    In previous versions of Mac OS x, I was able to select a part of the message (text / iMessage) in the Messages application. Now, if I try to do the same, Tapback is enabled. It's really annoying, as I often have to copy the entire message body, paste into an editor and then to do the editing.

    Which should not happen if you simply select the text of the message by double-clicking or click-and - drag. That action works the same way it always has.

    Tapback happen if you press and hold - in other words, if do not quickly move the cursor.

    If you are still unable to work, please review your Trackpad preferences. Maybe change a setting arbitrary will correct what you are experiencing. Check accessibility > mouse and Trackpad in the same way: change a setting to determine if what it fixes.

  • How to select several objects on the layers panel in Illustrator CC

    I have a work of guge and I need to select a small group (about 10-100) of objects from 4000 bunk and then group objects ' em/split-to-layers for ease of use (this is an infographic of the human body for medical institute)

    There IS NO way by selecting in the Web because they are overlapping and sometimes not visible at all.

    in CS5 there was a function to select several objects to the icon selection Alt + click - move on the right in the Layers panel.

    Now the mode duplication towers - on when I try to run it.

    Then.

    Ho I select several object without having to click through thousands of them? (I need to drag-select)

    IM totally frustrated.

    As long there is no deliberately locked object, you can do the following:

    Drag on the lock column in the layer panel

    Object > unlock all (there is a shortcut for this)

    -> unlocked objects are selected

  • How to select from multiple cuts manual header and line in SO?

    Hello!

    I have several manual discounts header and lines in Advanced Pricing. How to select in orders? I read somewhere that to apply a discount, just go to the line and press the "Discount", but I couldn't find this button anywhere. I remember before I am just pressing the lov (...) in the unit selling price and I can choose manual reduction (if I'm not mistaken), but now, when I pressed it, it only apply the first discount manual I have (I have defined it 2 manual sheds). Can someone help me with this? Is the mentioned "Discount" button was the lov (...) in the unit selling price?

    Thank you.

    Use the button Actions to "The sight adjustments." That should allow you to see and apply modifiers are qualified to order.

  • How to log on automatically to the apex and run a specific page / application

    Hi all.

    I would like to know if there is a way to connect automatically to the apex and run a specific page / application. I mean, invoke browser and necessary information for you connect (non-public user) and run a specific application (secure ina in if possible).

    Thanks in advance...!

    Hello

    Well, as a very crude test, you can set your authentication scheme being request Express authentication define specific users to Apex. Then, create one before the login process of header on the page of connection (101) to automatically open a session that contains:

    apex_authentication.login(
        p_username => :P101_USERNAME,
        p_password => :P101_PASSWORD );
    :P101_PASSWORD := NULL;
    

    conditional on P101_PASSWORD is not null.

    Then you can login using your username and password in the URL, for example

    f? p = YOURAPP:LOGIN:P101_USERNAME, P101_PASSWORD:username, password

    Rod West

  • How can I remove eventListener on the main time line off the loaded SWF?

    I have a Workbench where my main timeline is retouching of the marked sections. In one of the marked sections I have load and SWF file using greensock SWF Loader. In the loaded SWF file, there is a command where I need to remove/addEventListeners on the main timeline of the flash file in the loaded SWF file.

    The establishment with "MovieClip (parent.parent.parent.parent)." works for the navigation and loading and other functions. However, I get the error "1120: access of property unidetified" if I want to use a line of code like this:

    MovieClip (parent.parent.parent.parent) .mainNav_buttonsGroup_mc. Applications_b tn_mc.removeEventListener (MouseEvent.ROLL_OVER, overHandler_Applications_btn);

    I'm just writing this EventListeners again in the SWF file loading (thus repeating once again that they are specified on the main time line already) or there is a better method for her?

    appImgBtns_mc.testBtns2_mc.addEventListener(MouseEvent.CLICK, onClick_testBtns2);
    
    
    function onClick_testBtns2(event:MouseEvent) :void {
              /////////
                        ////disabling the button onClick by removeEventListener
                        //MovieClip(parent.parent.parent.parent).mainNav_buttonsGroup_mc.Applications_btn_mc.removeEventListener(MouseEvent.ROLL_OVER, overHandler_Applications_btn);
                        //MovieClip(parent.parent.parent.parent).mainNav_buttonsGroup_mc.Applications_btn_mc.removeEventListener(MouseEvent.ROLL_OUT, outHandler_Applications_btn);
                            //MovieClip(parent.parent.parent.parent).mainNav_buttonsGroup_mc.Applications_btn_mc.removeEventListener(MouseEvent.CLICK, onClick_Applications_btn);
                        ////coloring the button
            MovieClip(parent.parent.parent.parent).Applications_btn_timeLine.play();
      
                        //Products_btn_mc
                        //MovieClip(parent.parent.parent.parent).mainNav_buttonsGroup_mc.Products_btn_mc.addEventListener(MouseEvent.ROLL_OVER, overHandler_Products_btn);
                        //MovieClip(parent.parent.parent.parent).mainNav_buttonsGroup_mc.Products_btn_mc.addEventListener(MouseEvent.ROLL_OUT, outHandler_Products_btn);
                        //MovieClip(parent.parent.parent.parent).mainNav_buttonsGroup_mc.Products_btn_mc.addEventListener(MouseEvent.CLICK, onClick_Products_btn);
                        //discoloring the button
            MovieClip(parent.parent.parent.parent).Products_btn_timeLine.reverse();
      
      
              MovieClip(parent.parent.parent.parent).sourceVar_AppPopUpsLoader_fromPrdcts="images/app_images/original/icysophistication_new_tl.swf";
              MovieClip(parent.parent.parent.parent).gotoAndPlay("appPopUps_fromPrdcts");
    }
    
    

    You can communicate with the main timeline by dispatching events from the child swf file.

    When the child Swf is loaded, dispatches an event, i.e. - dispatchEvent (new Event ("DoTimeLineCode"));

    Then on your main timeline, listen for the event and perform the desired functions:

    MovieClip (root) .addEventListener ("DoTimeLineCode", mainTimeLineFunctions);

    function mainTimeLineFunctions(e:Event):void

    {

         MovieClip(root).Applications_btn_timeLine.play();

    etc...

    }

    ChasingMovieClip(parent.parent.parent.parent) has always been a losing battle for me. It's best practice to use event dispatchers and listeners to instantiate "things" from the parent child paradigm.

    ~ Chipleh

  • problem in the conversion of lines to a column

    I use Oracle 10 g on Linux. I'm trying to concatenate the rows returned by the query. Since there are more than 50 lines to concatenate, therefore, I used the getClobVal() function. There are two problems with this release:


    1. < E > at the beginning and end of the output.
    2. Double quotation marks is replaced by & quote;


    WITH T AS (
    SELECT '{"startDate":"01-JAN-2999","processName":"RUNNING_BALANCE_PROCESS"}' json_objects   FROM dual
    UNION
    SELECT '{"startDate":"01-JAN-2999","processName":"CONTRACT_SYNCHRONIZATION_PROCESS"}' json_objects   FROM dual                           
    UNION
    SELECT '{"startDate":"01-JAN-2999","processName":"MTI_PEAK_BALANCE_PROCESS"}' json_objects   FROM dual                                  
    UNION
    SELECT '{"startDate":"01-JAN-2999","processName":"MAINTAIN_CASHPOOL_PROCESS"}' json_objects   FROM dual                                 
    UNION
    SELECT '{"startDate":"01-JAN-2013","processName":"CIL_FXH_PURGE_PROCESS"}' json_objects   FROM dual                                     
    )
    SELECT  rtrim (xmlagg (XMLELEMENT (E, json_objects || ',')).getClobVal()) json
    FROM T
    
    
    
    JSON                                                                            
    --------------------------------------------------------------------------------
    <E>{&quot;startDate&quot;:&quot;01-JAN-2013&quot;,&quot;processName&quot;:&quot;
    CIL_FXH_PURGE_PROCESS&quot;},</E><E>{&quot;startDate&quot;:&quot;01-JAN-2999&quo
    t;,&quot;processName&quot;:&quot;CONTRACT_SYNCHRONIZATION_PROCESS&quot;},</E><E>
    {&quot;startDate&quot;:&quot;01-JAN-2999&quot;,&quot;processName&quot;:&quot;MAI
    NTAIN_CASHPOOL_PROCESS&quot;},</E><E>{&quot;startDate&quot;:&quot;01-JAN-2999&qu
    ot;,&quot;processName&quot;:&quot;MTI_PEAK_BALANCE_PROCESS&quot;},</E><E>{&quot;
    startDate&quot;:&quot;01-JAN-2999&quot;,&quot;processName&quot;:&quot;RUNNING_BA
    LANCE_PROCESS&quot;},</E>                                                       
                                                                                    
    1 row selected.
    

    Elya wrote:

    REPLACE converts CLOB VARCHAR2. The maximum size that could be 4000.

    The output generated when it is applied to the actual data consists of 8897 characters. Replace function worked correctly.

    True Yes sorry for my previous comment. I was wrong. REPLACE manages the CLOB. But this isn't the solution to your problem. You want to prevent the encoding of a certain nature while converting to XML. Using REPLACE you simply manage quotes, what other characters too can get encoded. For this you can do it like that.

    SQL> with t as  2  (  3  SELECT '{"startDate":"01-JAN-2999","processName":"RUNNING_BALANCE_PROCESS"}' json_objects   FROM dual  4  UNION  5  SELECT '{"startDate":"01-JAN-2999","processName":"CONTRACT_SYNCHRONIZATION_PROCESS"}' json_objects   FROM dual  6  UNION  7  SELECT '{"startDate":"01-JAN-2999","processName":"MTI_PEAK_BALANCE_PROCESS"}' json_objects   FROM dual  8  UNION  9  SELECT '{"startDate":"01-JAN-2999","processName":"MAINTAIN_CASHPOOL_PROCESS"}' json_objects   FROM dual 10  UNION 11  SELECT '{"startDate":"01-JAN-2013","processName":"CIL_FXH_PURGE_PROCESS"}' json_objects   FROM dual 12  ) 13  select dbms_xmlgen.convert 14         ( 15             xmlagg 16             ( 17                 xmlelement(A, json_objects || ',') 18             ).extract('A/text()').getclobval() 19           , 1 20         ) str 21    from t;
    
    STR--------------------------------------------------------------------------------{"startDate":"01-JAN-2013","processName":"CIL_FXH_PURGE_PROCESS"},{"startDate":"01-JAN-2999","processName":"CONTRACT_SYNCHRONIZATION_PROCESS"},{"startDate":"01-JAN-2999","processName":"MAINTAIN_CASHPOOL_PROCESS"},{"startDate":"01-JAN-2999","processName":"MTI_PEAK_BALANCE_PROCESS"},{"startDate":"01-JAN-2999","processName":"RUNNING_BALANCE_PROCESS"},
    
    SQL>
    
  • How to return rows by using the procedure?

    Example: There are 3 areas: A, B, C and each region has some people.

    create table person (name varchar2 (2), area varchar2 (2));

    insert into values('A1','A') of the person;  -1st rank

    insert into values('A2','A') of the person;  -line 2

    insert into values('A3','A') of the person;  -tier 3

    insert into values('A4','A') of the person;  -tier 4

    insert into values('B1','B') of the person;  -tier 5

    insert into values('C1','C') of the person;  -tier 6

    insert into values('C2','C') of the person;  -line 7

    result as follows:

    A, B AND C

    --------------

    A1 B1 C1

    A2 C2

    A3

    A4

    If we ' select * from person ", then we had all the lines.

    I want to now choose volunteers in all areas, the rule is to pick one person from each region ordered, until that N people are selected. If N = 6, the sequence is

    A1, A3, A2, B1, C1, C2

    and want to return lines 1,5,6,2,7,3 (order of lines is not important) of the person.

    How to create a procedure for this? And I want to return as rows returned by a select phrase. (can be easily filled in a DataTable object and then be used in a program).

    Thank you!!

    Hello

    2985493 wrote:

    Thank you. Could you write a procedure to do the job? This is just an example, real choice rule is complicated enough to be used by the procedure and the cursor. I wonder how do to write a procedure returns the result as a select phrase.

    Here's one way:

    VARIABLE c REFCURSOR

    CREATE OR REPLACE PROCEDURE top_by_area

    (csr ON SYS_REFCURSOR

    , n_to_return IN PLS_INTEGER: = 6

    )

    IS

    BEGIN

    OPEN FOR CSR

    WITH got_area_num AS

    (

    SELECT name, area

    OF the person

    ORDER BY ROW_NUMBER () (PARTITION BY AREA

    ORDER BY name

    )

    area

    )

    SELECT name, area

    ROWNUM AS r_num

    OF got_area_num

    WHERE ROWNUM<=>

    ORDER BY r_num

    ;

    END top_by_area;

    /

    DISPLAY ERRORS

    EXEC top_by_area (: c);

    PRINTING: c

    PRINT the output of the command, given your sample data is:

    R_NUM DOMAIN NAME

    ---- ---- --------

    A1 1

    B1 B 2

    C1, C 3

    A2 4

    C2 C 5

    A3 A 6

    It's just a way to create and test the procedure.  I don't know how you plan to use it.

  • How to select and default hightlight the first line in a programmatic Table(ADF Table created based on a SortableModel) ADF.

    Hi all


    We use JDeveloper Studio Edition Version 12.1.3.0.0 and deployed on GlassFish Server Open Source Edition 3.1.2.2 (build 5) and connect to the SQLServer database.


    We created a table ADF programming related to a SortableModel created programmatically to a bean.


    We need to select and highlight the first row in the table just after making it to retrieve data based on the first line.


    We tried the based on the following thread: How to call the bean support just after JSFF / page fragment loads? and a few other posts online, but it does not work very well.


    W has created a hidden text in the bottom of the JSF model as follows:


    < af:table varStatus = "rowStat" Summary = "table" value = "#{pageFlowScope.crudBean.dynamicTable.collectionModel} '"

    Rows = "#{pageFlowScope.crudBean.dynamicTable.collectionModel.RowCount} '"

    contentDelivery = 'immediate' var = 'row' rendered = 'true '.

    Binding = "#{backingBeanScope.crudBackingBean.tasksTable} '"

    selectionListener = "#{backingBeanScope.crudBackingBean.customListener} '"

    "rowSelection ="single"id ="t1"partialTriggers =": pt_gr2 "columnStretching =" column: clmn0 ">

    < af:forEach items = "#{pageFlowScope.crudBean.dynamicTable.columnNames}" var = 'name' varStatus 'vs' = > "

    < af:column sortable = "true" sortProperty rowHeader = "#{name}" = "no style" headerText = "#{pageFlowScope.crudBean.dynamicTable.columnLabel [name]}" "

    inlineStyle = "width: 100px;"  ID = "clmn$ {vs.index}" >

    < af:activeOutputText value = "#{row [name]}" id = "aot1" / >

    < / af:column >

    < / af:forEach >

    < / af:table >

    ....


    < af:outputText id = "hiddenOutputTextId" visible = "false" value = "#{backingBeanScope.crudBackingBean.afterPageLoad} '"

    Binding="#{backingBeanScope.crudBackingBean.hiddenOutputText}"/ >

    And we have added the code to the bean to support below:

    public String getAfterPageLoad() {}

    If (!.) {AdfFacesContext.getCurrentInstance () .isPostback ()}

    selectFirstRowInTasksTable();

    }

    Return afterPageLoad;

    }

    public void selectFirstRowInTasksTable() {}

    try {}

    RKS RowKeySet = new RowKeySetImpl();

    RowKeySet rksEmpty = new RowKeySetImpl();

    Model CollectionModel = tasksTable.getValue ((CollectionModel));

    ROWCOUNT int = model.getRowCount ();

    If (rowcount > 0) {}

    model.setRowIndex (0);

    Key of the object = model.getRowKey ();

    RKS. Add (Key);

    tasksTable.setSelectedRowKeys (rks);

    SelectionEvent selectEvent =

    new SelectionEvent (tasksTable.getSelectedRowKeys (), rks, tasksTable);

    selectEvent.queue ();

    customListener (selectEvent); / / to retrieve data

    AdfFacesContext.getCurrentInstance () .addPartialTarget (tasksTable);

    }

    } catch (Exception e) {}

    }

    }

    I think that () selectEvent.queue; should work even without calling the customerListener, but it is not working in all cases.

    What is the problem in my code?



    Have you tried to bind property of 'selectedRowKeys' to selection configuration / bean there?

    Something like:

    public RowKeySet getSelectedRKS() {
        if (rks == null) {
            // make first record as selected
            // create RowKeySet and assign it to rks variable(where rks is variable defined in bean with some scope higher than request scope)
        }
        return rks;
    }
    

    Dario

Maybe you are looking for