Use Oracle analysis functions to randomly extract N records

Source: Internet
Author: User

Use Oracle analysis functions to randomly extract N records

Simulate a song table with a song ID and Author ID, and initialize some data

Create table music (
 
Music_id int primary key,

Userid int

);

Insert into music (music_id)

Select rownum rn from dual connect by level <1000;

Update music set userid = mod (music_id, 5 );

Commit;
Requirements:
Each author randomly selects three of his works.
 
The SQL statement is as follows:
 

Select * from
 
(

Select music_id, userid, ROW_NUMBER () OVER (partition by userid order by dbms_random.random () rn from music

)

Where rn <= 3;
 
First execution:

Second execution:

This method is only effective for Oracle (using its analysis functions)

Detailed examples of Oracle function GREATEST Functions

Single-row conversion functions of Oracle Functions

Oracle functions that generate dynamic prefixes and auto-increment numbers

Replace () for Oracle Functions ()

Oracle Functions

Differences in case and decode usage and Performance Comparison of Oracle Functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.