Can you please explain how this query is fetching the rows?

here is a query to find the top 3 salaries. But the thing is that i am now able to understand how its working to get the correct data :How the data in the alias table P1 and P2 getting compared. Can you please explain in some steps.
SELECT MIN(P1.SAL) FROM PSAL P1, PSAL P2
WHERE P1.SAL >= P2.SAL
GROUP BY P2.SAL
HAVING COUNT (DISTINCT P1.SAL) <=3 ;
here is the data i used :
SQL> select * from psal;
NAME SAL
able 1000
baker 900
charles 900
delta 800
eddy 700
fred 700
george 700
george 700
Regards,
Renu

... Please help me in understanding the query.
Your query looks like anything but a Top-N query.
If you run it in steps and analyze the output at the end of each step, then you should be able to understand what it does.
Given below is some brief information on the same:
test@ora>
test@ora> --
test@ora> -- Query 1 - using the non-equi (theta) join
test@ora> --
test@ora> with psal as (
  2    select 'able' as name, 1000 as sal from dual union all
  3    select 'baker',   900 from dual union all
  4    select 'charles', 900 from dual union all
  5    select 'delta',   800 from dual union all
  6    select 'eddy',    700 from dual union all
  7    select 'fred',    700 from dual union all
  8    select 'george',  700 from dual union all
  9    select 'george',  700 from dual)
10  --
11  SELECT p1.sal AS p1_sal, p1.NAME AS p1_name, p2.sal AS p2_sal,
12         p2.NAME AS p2_name
13    FROM psal p1, psal p2
14   WHERE p1.sal >= p2.sal;
    P1_SAL P1_NAME     P2_SAL P2_NAME
      1000 able          1000 able
      1000 able           900 baker
      1000 able           900 charles
      1000 able           800 delta
      1000 able           700 eddy
      1000 able           700 fred
      1000 able           700 george
      1000 able           700 george
       900 baker          900 baker
       900 baker          900 charles
       900 baker          800 delta
       900 baker          700 eddy
       900 baker          700 fred
       900 baker          700 george
       900 baker          700 george
       900 charles        900 baker
       900 charles        900 charles
       900 charles        800 delta
       900 charles        700 eddy
       900 charles        700 fred
       900 charles        700 george
       900 charles        700 george
       800 delta          800 delta
       800 delta          700 eddy
       800 delta          700 fred
       800 delta          700 george
       800 delta          700 george
       700 eddy           700 eddy
       700 eddy           700 fred
       700 eddy           700 george
       700 eddy           700 george
       700 fred           700 eddy
       700 fred           700 fred
       700 fred           700 george
       700 fred           700 george
       700 george         700 eddy
       700 george         700 fred
       700 george         700 george
       700 george         700 george
       700 george         700 eddy
       700 george         700 fred
       700 george         700 george
       700 george         700 george
43 rows selected.
test@ora>
test@ora>This query joins PSAL with itself using a non equi-join. Take each row of PSAL p1 and see how it compares with PSAL p2. You'll see that:
- Row 1 with sal 1000 is >= to all sal values of p2, so it occurs 8 times
- Row 2 with sal 900 is >= to 9 sal values of p2, so it occurs 7 times
- Row 3: 7 times again... and so on.
- So, total no. of rows are: 8 + 7 + 7 + 5 + 4 + 4 + 4 + 4 = 43
test@ora>
test@ora> --
test@ora> -- Query 2 - add the GROUP BY
test@ora> --
test@ora> with psal as (
  2    select 'able' as name, 1000 as sal from dual union all
  3    select 'baker',   900 from dual union all
  4    select 'charles', 900 from dual union all
  5    select 'delta',   800 from dual union all
  6    select 'eddy',    700 from dual union all
  7    select 'fred',    700 from dual union all
  8    select 'george',  700 from dual union all
  9    select 'george',  700 from dual)
10  --
11  SELECT p2.sal AS p2_sal,
12         COUNT(*) as cnt,
13         COUNT(p1.sal) as cnt_p1_sal,
14         COUNT(DISTINCT p1.sal) as cnt_dist_p1_sal,
15         MIN(p1.sal) as min_p1_sal,
16         MAX(p1.sal) as max_p1_sal
17    FROM psal p1, psal p2
18   WHERE p1.sal >= p2.sal
19  GROUP BY p2.sal;
    P2_SAL        CNT CNT_P1_SAL CNT_DIST_P1_SAL MIN_P1_SAL MAX_P1_SAL
       700         32         32               4        700       1000
       800          4          4               3        800       1000
       900          6          6               2        900       1000
      1000          1          1               1       1000       1000
test@ora>
test@ora>Now, if you group by p2.sal in the output of query 1, and check the number of distinct p1.sal, min of p1.sal etc. you see that for p2.sal values - 800, 900 and 1000, there are 3 or less p1.sal values associated.
So, the last 3 rows are the ones you are interested in, essentially. As follows:
test@ora>
test@ora> --
test@ora> -- Query 3 - GROUP BY and HAVING
test@ora> --
test@ora> with psal as (
  2    select 'able' as name, 1000 as sal from dual union all
  3    select 'baker',   900 from dual union all
  4    select 'charles', 900 from dual union all
  5    select 'delta',   800 from dual union all
  6    select 'eddy',    700 from dual union all
  7    select 'fred',    700 from dual union all
  8    select 'george',  700 from dual union all
  9    select 'george',  700 from dual)
10  --
11  SELECT p2.sal AS p2_sal,
12         COUNT(*) as cnt,
13         COUNT(p1.sal) as cnt_p1_sal,
14         COUNT(DISTINCT p1.sal) as cnt_dist_p1_sal,
15         MIN(p1.sal) as min_p1_sal,
16         MAX(p1.sal) as max_p1_sal
17    FROM psal p1, psal p2
18   WHERE p1.sal >= p2.sal
19  GROUP BY p2.sal
20  HAVING COUNT(DISTINCT p1.sal) <= 3;
    P2_SAL        CNT CNT_P1_SAL CNT_DIST_P1_SAL MIN_P1_SAL MAX_P1_SAL
       800          4          4               3        800       1000
       900          6          6               2        900       1000
      1000          1          1               1       1000       1000
test@ora>
test@ora>
test@ora>That's what you are doing in that query.
The thing is - in order to find out Top-N values, you simply need to scan that one table PSAL. So, joining it to itself is not necessary.
A much simpler query is as follows:
test@ora>
test@ora>
test@ora> --
test@ora> -- Top-3 salaries - distinct or not; using ROWNUM on ORDER BY
test@ora> --
test@ora> with psal as (
  2    select 'able' as name, 1000 as sal from dual union all
  3    select 'baker',   900 from dual union all
  4    select 'charles', 900 from dual union all
  5    select 'delta',   800 from dual union all
  6    select 'eddy',    700 from dual union all
  7    select 'fred',    700 from dual union all
  8    select 'george',  700 from dual union all
  9    select 'george',  700 from dual)
10  --
11  SELECT sal
12  FROM (
13    SELECT sal
14      FROM psal
15    ORDER BY sal DESC
16  )
17  WHERE rownum <= 3;
       SAL
      1000
       900
       900
test@ora>
test@ora>
test@ora>And for Top-3 distinct salaries:
test@ora>
test@ora> --
test@ora> -- Top-3 DISTINCT salaries; using ROWNUM on ORDER BY on DISTINCT
test@ora> --
test@ora> with psal as (
  2    select 'able' as name, 1000 as sal from dual union all
  3    select 'baker',   900 from dual union all
  4    select 'charles', 900 from dual union all
  5    select 'delta',   800 from dual union all
  6    select 'eddy',    700 from dual union all
  7    select 'fred',    700 from dual union all
  8    select 'george',  700 from dual union all
  9    select 'george',  700 from dual)
10  --
11  SELECT sal
12  FROM (
13    SELECT DISTINCT sal
14      FROM psal
15    ORDER BY sal DESC
16  )
17  WHERE rownum <= 3;
       SAL
      1000
       900
       800
test@ora>
test@ora>
test@ora>You may also want to check out the RANK and DENSE_RANK analytic functions.
RANK:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions123.htm#SQLRF00690
DENSE_RANK:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions043.htm#SQLRF00633
HTH
isotope

Similar Messages

  • Hi guys, can you please explain how to perform automatic system scan with CleanApp - it looks like it wants me to manually chose files to delete and I just want an automatic scan (like cleanmymac does)

    Hi guys, can you please explain how to perform automatic system scan with CleanApp - it looks like it wants me to manually chose files to delete and I just want an automatic scan (like cleanmymac does)

    Slowness...First Try using Disk Utility to do a Disk Repair, as shown in this link, while booted up on your install disk.
      You could have some directory corruption. Let us know what errors Disk Utility reports and if DU was able to repair them. Disk Utility's Disk Repair is not perfect and may not find or repair all directory issues. A stronger utility may be required to finish the job.
      After that Repair Permissions. No need to report Permissions errors....we all get them.
    Here's Freeing up Disk Space.
    DALE

  • In Pages 09 we can do Mail Merge and Import Styles from a document. Can someone please explain how we can do this with the new version of Pages 5.1. Even Apple solutions are only valid for Pages Version 09. What a DOWN GRADE!

    In Pages 09 we can do Mail Merge and Import Styles from a document. Can someone please explain how we can do this with the new version of Pages 5.1. Even Apple solutions are only valid for Pages Version 09. What a DOWN GRADE! Thank god Pages 09 is still there.

    …and the other 98 missing features.
    Just use Pages '09, which should be in your Applications/iWork folder.
    Rate/review Pages 5 in the App Store.
    Peter

  • I am using iPhone 3GS. I am living in Saudi Arabia. I cannot find the directions with in GCC contries in the Navigation Application "COMPASS" of iphone. Can you please explain me how to work on it??

    I am using iPhone 3GS. I am living in Saudi Arabia. I cannot find the directions with in GCC contries in the Navigation Application "COMPASS" of iphone. Only the map is displayed. I am not gtting the directions or information when I use it. Can you please explain me how to work on it??

    See http://kb.mozillazine.org/Editing_configuration#How_to_edit_configuration_files
    Add code to [http://kb.mozillazine.org/UserChrome.css userChrome.css] below the @namespace line.
    <pre><nowiki>@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); /* only needed once */
    #context-sendlink {display:none !important;}</nowiki></pre>
    See also http://kb.mozillazine.org/Chrome_element_names_and_IDs

  • Can somebody please explain how to format and then reinstall Mac lion10.7 without cd

    can somebody please explain how to format and then reinstall Mac lion10.7 without cd

    You will need either an Ethernet or Wifi Connection to the Internet - USB Mobile device is not supported.
    If you already have Lion installed you can boot to Recovery with Command R and use the Disk Utility to erase the Macintosh HD and then reinstall the OS from the Mac OS X Utilities.
    You will need the Apple Id used for purchase if the Mac did not ship with Lion installed originally.
    If you want to repartition the HDD you can use the Recovery Disk Assistant to make a recovery USB drive
    http://support.apple.com/kb/DL1433
    http://support.apple.com/kb/HT4848
    As Always - Back up the Mac before erasing unless you are confident there is absolutely nothing on the mac that you might possibly need later.
    If the machine is a 2011 build or later you might be able to boot to Internet Recovery with Command Option R

  • Could you please explain how to work with Outlier Correction

    could you please explain how to work with Outlier Correction

    Hi sr,
    Actually an outlier correction is an historical value that lies the tolerance lane.
    the apo sys calculate this tolerance lane on the basis of the sigma factor.
    It then correct any historical value that lies outside the upper or lower band of this tolerance lane.
    So, that it corresponds to the calculated ex- post value for that point in time.
    this option is available in Master forecast profile /sapapo/mc96b in Univariate profile( control parameters) tab.
    If you have set the outlier correction indicator, then the sys first calculate an ex-post forecast with the selected forecasting techniques.
    In the next step, the sys calculates a tolerance threshold T.
    where T is calculated as T = sigma * MAD (Mean Absolute Deviation)
    Here the Sigma factor defines the width of the tolerance rangefor automatic outlier correction.
    it defines the permissible number of standard deviations.
    A small sigma factor means a low tolerance, and a large number of outliers that are detected and corrected.
    The default Sigma factor is 1.25.
    If you set the Sigma factor, SAP recommends that you set it betw 0.6 and 2.
    I hope this is helpful for you.
    Regards,
    Pullaiah

  • Hello  can you please advise how to split a multiple VCF card (that includes 1000s of indivudual cards)

    hello 
    i am using MCbackup on my iphone4 and did backup all my contacts into 1 single VCF card (consisting of 1000s individual vcf cards)
    can you please advise how to split a multiple VCF card (that includes 1000s of indivudual cards) in order to save them in outlook 2007 as backup thanks

    This is more related to Office issue, I’d like to suggest you post this issue to Office forum. 
    Here is the link: http://support.microsoft.com/gp/gp_newsgroups_master
    ***Don't forget to mark helpful or answer***
    **Note:(My posts are provided “AS IS” without warranty of any kind)

  • Hi there, i have Q i have excel file it need to be block with password. Could you please explain how i make password protect to Excel document

    Hi there,
    i have Q i have excel file it need to be block with password. Could you please explain how i make password protect to Excel document
    Thanks

    On the File menu, click Save As.
    On the Tools menu, click General Options.
    Do either or both of the following:
    If you want users to enter a password before they can view the workbook, type a password in the Password to open box, and then click OK.
    If you want users to enter a password before they can save changes to the workbook, type a password in the Password to modify box.
    NOTE   Unlike passwords you specify in the Password to open box, passwords you specify in the Password to modify box are not encrypted. These passwords are only meant to give specific users permission to modify workbook data. For optimal password security, it's best to assign both passwords. An encrypted password to access the workbook, and one to provide specific users with permission to modify its content. IMPORTANT   Use strong passwords that combine uppercase and lowercase letters, numbers, and symbols. Weak passwords don't mix these elements. Strong password: Y6dh!et5. Weak password: House27. Use a strong password that you can remember so that you don't have to write it down.
    If you want to use a different encryption type, click Advanced, click the type you want in the Choose an encryption type list, and then click OK.
    If needed, specify the number of characters you want in the Choose a key length box.
    NOTE   Document property encryption is enabled by default for most encryption types and providers. It prevents unauthorized users from viewing summary and custom file properties (such as the author or any custom file information) in theProperties dialog box. When users right-click the password-protected file, and then click Properties, information won't be available on the Summary tab and Customtab. Authorized users, however, can open the file and view all file properties (Filemenu, Properties command). To disable document property encryption, clear theEncrypt document properties check box.
    Click OK.
    When prompted, retype your passwords to confirm them.
    Click Save.
    If prompted, click Yes to replace the existing workbook.
    NOTE   You can also secure a workbook with a password on the Security tab of the Options dialog box (Tools menu, Options command).

  • Can someone please explain how I download all my songs from the cloud without having to tick each cloud individually for each song

    Can someone please explain how to download all my songs from cloud without having to tick each cloud individually

    Music > iTunes Store > Music Quick Links > Purchased > Not in My Library > Download All.
    tt2

  • I bought a used iphone from a friend and I am not able to use it in Ethiopia. It is carrier blocked. Can you please help how could I unlock my iphone 4?.

    I bought a used iphone from a friend and I am not able to use it in Ethiopia. It is carrier blocked. Can you please help how could I unlock my iphone 4?.

    Unlikely as you do not meet there requirements for unlocking.
    Have your friend the provided the phone contact them.  Based on your statements I am concluding he was or still is an AT&T customer, that is one of the requirements of getting the device unlocked.

  • Trying to download indesign for mac, photoshop and illustrator trial which i require immediately but your website is crashing/saying there is an error. Can you please advise when this will be rectified?

    trying to download indesign for mac, photoshop and illustrator trial which i require immediately but your website is crashing/saying there is an error. Can you please advise when this will be rectified?

    WHatever issues you have are specifuc to your local system, not Adobe. Since you have not provided any shred of useful,technical details such as system info nobody can tell you anything.
    Mylenium

  • Can you please explain in detail about the T-Code SM59

    Can you please explain in detail about the T-Code SM59

    Hi Raja,
    detailed explanation is already available over help.sap.com.
    For your ready reference check below links
    http://help.sap.com/saphelp_spm21_bw/helpdata/en/57/898009a859493a8bce56caaf0f8e13/frameset.htm
    http://help.sap.com/saphelp_webas610/helpdata/en/da/11df3a9b10355ae10000000a11405a/frameset.htm
    http://help.sap.com/saphelp_snc70/helpdata/en/3f/7ffb40ef74f923e10000000a155106/frameset.htm
    Regards
    Jitender

  • I have deleted my sons apple id and data from his old phone by accident as i thought i was resetting it for me to use and now he has lost everything on his new phone and his id etc does not work.  Can someone please explain how i am able to retrieve

    Can someone please shed some light on this???
    I thought i was resetting my son's iphone 4 so that I could use it. But I seem to have erased his icloud/apple id and all of his data from his new phone too.  His Apple ID doesnt work and cant be accessed as it now says it is disabled.  I have tried the iforgot.apple.com website without success and have no idea how to rectify.  I have requested a password change to his email address but that is not working either.
    Please help? 

    That sounds confusing.  First off, don't be too worried. There's practically no way to actually delete an Apple ID or it's purchase history.  You should be able to get to it back somehow.  Secondly, that's likely something that you'll need to talk to a real person on the phone for since it likely requires you to explain that you need access on behalf of your son, (who probably just set some security questions or an email address that you didn't know he put in.)  Just call the appropriate AppleCare phone line (800-APL-CARE in the USA, or see the link below for other countries) and tell them you want to talk about an iCloud account security question.
    Phone Support: Contact Apple for support and service - Apple Support

  • Can somebody please simplify/tune this query?

    Hi,
    Can somebody please simplify this query?
    It's a little urgent. Currently this query is taking 10 mins to run.
    Thank you so much,
    vasu
    Purpose:
    First Child Case Ind =
    Get Parent Case for this case.
    Get all child cases for this parent case.
    Arrange them in ascending order by create Date.
    If the first case (eldest case) is the case in question,
    then Y
    else N
    Query:
    SELECT THIS_CASE.OBJID THIS_CASE_OBJID,
    PARENT.PARENT_OBJID,
    (CASE
    WHEN PARENT.FIRST_CHILD_OBJID = THIS_CASE.OBJID
    THEN 'Y'
    ELSE 'N'
    END) IS_FIRST_CHILD_CASE
    FROM SA.TABLE_CASE THIS_CASE,
    (SELECT PARENT_OBJID,
    CHILD_OBJID FIRST_CHILD_OBJID
    FROM (SELECT PARENT_CASE.OBJID PARENT_OBJID,
    CHILD_CASE.OBJID CHILD_OBJID,
    CHILD_CASE.CREATION_TIME,
    ROW_NUMBER() OVER (PARTITION BY PARENT_CASE.OBJID
    ORDER BY CHILD_CASE.CREATION_TIME ASC) ROW_NUM
    FROM SA.TABLE_CASE PARENT_CASE,
    SA.TABLE_CASE CHILD_CASE
    WHERE PARENT_CASE.OBJID = CHILD_CASE.CASE_VICTIM2CASE
    WHERE ROW_NUM = 1
    ) PARENT
    WHERE THIS_CASE.CASE_VICTIM2CASE = PARENT.PARENT_OBJID(+)

    Thank you for the quick reply.
    Here is the explain plan:
    Operation     Object Name     Rows     Bytes     Cost
    SELECT STATEMENT Optimizer Mode=CHOOSE          2 M          32831
    HASH JOIN OUTER          2 M     130 M     32831
    TABLE ACCESS FULL     SA.TABLE_CASE     2 M     24 M     21550
    VIEW          307 K     11 M     10130
    WINDOW SORT PUSHED RANK          307 K     7 M     10130
    MERGE JOIN          307 K     7 M     8666
    TABLE ACCESS BY INDEX ROWID     SA.TABLE_CASE     307 K     4 M     1266
    INDEX FULL SCAN     SA.IND_CASE_VICTIM2CASE     307 K          738
    SORT JOIN          2 M     19 M     7400
    INDEX FAST FULL SCAN     SA.PK_TABLE_CASE     2 M     19 M     785
    Please let me know.
    Thank you.

  • Can any body explain me this query?   select 'alter index '||index_name||' monitoring usage' as index_monitor from user_indexes where index_name='EMP';

    Initially i've a put an index of emp table in monitoring state..
    later i've got this query
    select 'alter index '||index_name||' monitoring usage' as index_monitor from user_indexes where index_name='EMP';
    can any body explain me what is the meaning of this query...
    and how do that query in the strings of projection area works....
    i'm totally confused
    thank you in advance.

    This is referred to as SQL generating SQL.  It is most useful when you  need to generate SQL statements for all indexes or indexes for one user.  After generating the text you then would execute it in SQLPlus or the tool of your choice.  If you combine this with a spool statement, SPOOL MyGeneratedScript.SQL you can run it with @MyGeneratedScript in SQLPlus.  I combine this into a script which generates the file, calls the editor so you can look it over and then executes it.  Here is an example of moving indexes to a different tablespace.
    -- UTL_Move_Indexs_To_New_TableSpace_Script.SQL
    /* This script will grab all the tables out of the specified source tablespace
    ** and move them into the specified target tablespace.  Ensure the the target
    ** exists and has sufficient room.  You must be logged in as the table owner.
    ACCEPT v_source_tablespace_name PROMPT 'Enter source tablespace name: '
    ACCEPT v_target_tablespace_name PROMPT 'Enter target tablespace name: '
    SET HEADING OFF
    SET FEEDBACK OFF
    SET TERMOUT OFF
    SET ECHO OFF
    SPOOL _move_index.SQL
    SELECT    'ALTER INDEX '
           || ndx.owner
           || '.'
           || ndx.index_name
           || CHR (10)
           || 'REBUILD '
           || CHR (10)
           || 'TABLESPACE '
           || UPPER ('&v_target_tablespace_name')
           || ';'
             sql_statement
    FROM   dba_indexes ndx
    WHERE      ndx.tablespace_name = UPPER ('&v_source_tablespace_name')
           AND ndx.index_type <> 'LOB'
    ORDER BY ndx.owner,
             ndx.index_name;
    SPOOL OFF
    --Edit the move script
    EDIT _move_index
    --Reset parameters.
    SET TERMOUT ON
    PAUSE Hit Ctrl+C to ABORT, any key to CONTINUE,
    -- Run the move script
    SPOOL  Move_Indexs_To_New_TableSpace.LOG
    @_move_index
    SPOOL OFF
    --Reset parameters.
    SET TERMOUT on
    SET FEEDBACK on
    SET HEADING on
    Marcus Baocn

Maybe you are looking for

  • How to connect my ipod with my mac

    Hello... I'm trying to connect my ipod touch with my mac book pro and for some reason the ipod is not paired, it is conected and the mac is finding the ipod but not pairing it The arror i get at my ipod is: Make sure "maci" (my mac name) is turned on

  • Problems emailing photos from iPhoto

    When using Iphoto to email pictures from the IMac - the pictures reflect the correct pictues emailed on the IMac - however the pictures showing up in the persons email are not the ones I chose to send - for instance if I send 10 different pictures on

  • Integrate SSRS Native Mode with Sharepoint 2013

    Hi, I have read numerous posts that go back and forth on the question "is SSRS Native Mode supported to work with SharePoint 2013?" and it seems like the answer is no, it is not. Even with SP1 like some people suggested it seems like it is impossible

  • Am new to java

    how to evaluate a flow chart using java. a condition given in the decision box and the values given should be evaluated finally.

  • Automated script to load files

    Hi , i have a procudure (pl/Sql) that loads a dat files to oracle tables, taking a file name as input parameter. i manually execute this pl/sql on daily basis which usually takes 30 min for one file. but now due to some issue in data i will have to t