A small Oracle subquery exercise

Source: Internet
Author: User

I was lying in bed last night watching Oracle (recently studying this). My roommate gave me a question and asked me to try it. The questions are as follows:

If the table structure is as follows, select the information of the top three persons whose score is the same (if the score is the same, it is counted as the same) and the table name is test:

NAME GRADE
------------------------------
Kate 80
Jenny 80
Daring 85
Agony 85
Xxx 90
Yyy 60

 

I thought about the following points yesterday:

1. First, you must sort them.

2. subquery

3. Since Oracle does not have TopN, you can only use the rownum pseudo column.

4. Because duplicate scores can be obtained, consider using distinct or grouping.

 

After testing, my answer is as follows:

Select * from test
Where grade in (

Select grade from (

Select distinct grade from test

Order by grade desc

)

Where rownum <4

)

Order by grade desc;

 

Or

Select * from test
Where grade in (

Select grade from (

Select grade from test

Group by grade

Order by grade desc

)

Where rownum <4

)

Order by grade desc;

 

The above two methods have similar ideas, except that the preceding distinct keyword is used to filter duplicates. The following methods are implemented by grouping. The idea of implementation remains unchanged.

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.