How to write better my query

Hello

on 11.2.0.4

I have two tables:

creation scripts are attached.

Capture.PNG

And I wrote a query to search for the students in which all their friends are in different qualities of themselves. Return the students names and ranks.

Here's my query and it works fine. But can it be written better? More effectively?

Select friend f, h1 highschooler, f.id1, h1.name, h1.grade, f.id2, h2.name, h2.grade

H2 highschooler where h1.id = f.id1 and h2.id = f.id2 and h1.grade <>h2.grade and f.id1 not in

(by selecting f1.id1 in friend f1, h3 highschooler,

highschooler h4 where h3.id = f1.id1 and h4.id = f1.id2 and h3.grade = h4.grade)

Thank you and best regards.

Step has)

count(*) over(partition by id1) cnt

It counts how many ID2 are there in each ID1

Step B)

count(decode(h.grade, h1.grade, null, 1)) over(partition by id1) f1

This does 2 things

Step 1

decode(h.grade, h1.grade, null, 1)

If grade ID1 is equal to the rank of ID2 return NULL otherwise if its different 1 return

Note: COUNTY does not have the value NULL. This is the reason for return null.

Step 2

count() over(partition by id1) f1

This is essentially considered how ID2 can have a different category than for each ID1 ID1

When we filter for step A is equal to step B, then it will give ID1 which all ID2 are in a different category

Tags: Database

Similar Questions

  • How to write the select query for it

    Hello

    I had an html form and the area I drop down and he needs to select several values in the drop-down box. When I select multiple values then I have to write the query to SQL select statement.

    When I try to write the select statement and trying to run I get the error message.

    Select * from Table

    where emo_no = '1,2,3 '.

    That's how I write the query please suggest me how to write the query to select several values in the drop-down box.

    Thank you

    Use the keyword sql 'in '.  If you don't know how, I've heard good things about the book Teach Yourself SQL in 10 Minutes by Ben Forta.

  • How to write this Simple query?

    Select * from student

    where

    (select count (first_name) of student) > 1;

    Basically I want a list of student table where the counties of first names are more than 1. However he shows me the output for

    Select * from student;

    any suggestions?

    Hello

    2776946 wrote:

    Select * from student

    where

    (select count (first_name) of student) > 1;

    Basically I want a list of student table where the counties of first names are more than 1. However he shows me the output for

    Select * from student;

    any suggestions?

    Think about it.  The subquery tells you the number of rows in all of the table have a first name.  It will always tell you the number of rows in all of the table name.  You don't want to know how many rows in the table have a name, you want to know how many rows in the table have the same name.

    One way to do is a correlated subquery:

    Select *.

    student m-m is for hand query

    where)

    SELECT count (*)

    student s-s is for the subquery

              where s.first_name = m.first_name

    )  > 1

    ;

  • How to write a hierarchical query so that only the child nodes are displayed?

    Hi all

    I have a hierarchical query that I use in an area of tree demand APEX and there are nodes that have no children and I am trying to find a way to not display these nodes. Essentially if the user does not have to develop a lot of knots to know that nothing exists at the most detailed level.

    The data are based on the Oracle Fusion FND tables but for example purposes here is enough data to illustrate my question:


    create table APPL_TAXONOMY_HIERARCHY (SOURCE_MODULE_ID varchar2(30), TARGET_MODULE_ID varchar2(30));
    create table APPL_TAXONOMY_TL (module_id varchar2(30), description varchar2(100), user_module_name varchar2(30), language varchar2(5));
    create table APPL_TAXONOMY (MODULE_ID    varchar2(30),    MODULE_NAME    varchar2(30), MODULE_TYPE varchar2(10),    MODULE_KEY varchar2(30));
    create table TABLES (table_name varchar2(30), module_key varchar2(30));
    
    

    insert into APPL_TAXONOMY_TL values ('1', null, 'Oracle Fusion', 'US' );
    insert into APPL_TAXONOMY_TL values ('2', null, 'Financials', 'US' );
    insert into APPL_TAXONOMY_TL values ('3', null, 'Human Resources', 'US' );
    insert into APPL_TAXONOMY_TL values ('20', null, 'Accounts Payable', 'US' );
    insert into APPL_TAXONOMY_TL values ('10', null, 'General Ledger', 'US' );
    
    insert into APPL_TAXONOMY_HIERARCHY values ('1', 'DDDDDDDD');
    insert into APPL_TAXONOMY_HIERARCHY values ('2', '1');
    insert into APPL_TAXONOMY_HIERARCHY values ('3', '1');
    insert into APPL_TAXONOMY_HIERARCHY values ('4', '1');
    insert into APPL_TAXONOMY_HIERARCHY values ('10', '2');
    insert into APPL_TAXONOMY_HIERARCHY values ('20', '2');
    
    insert into APPL_TAXONOMY values ('1', 'Fusion', 'PROD', 'Fusion');
    insert into APPL_TAXONOMY values ('2', 'Financials', 'FAMILY', 'FIN');
    insert into APPL_TAXONOMY values ('10', 'GL', 'APP', 'GL');
    insert into APPL_TAXONOMY values ('3', 'Human Resources', 'FAMILY', 'HR');
    insert into APPL_TAXONOMY values ('20', 'AP', 'APP', 'AP');
    
    insert into tables values ('GL_JE_SOURCES_TL','GL');
    insert into tables values ('GL_JE_CATEGORIES','GL');
    

    My hierarchical query is as follows:

    with MODULES as
    (
    SELECT h.source_module_id, b.user_module_name, h.target_module_id
          FROM APPL_TAXONOMY_HIERARCHY H,
          APPL_TAXONOMY_TL B,
    APPL_TAXONOMY VL
    where H.source_module_id = b.module_id
    and b.module_id = vl.module_id
    and vl.module_type not in ('PAGE', 'LBA')
    UNION ALL
    select distinct table_name, table_name,  regexp_substr(table_name,'[^_]+',1,1) 
    from TABLES --needed as a link between TABLES and APPL_TAXONOMY
    union all
    select module_key as source_module_id, module_name as user_module_name, module_id as target_module_id  from appl_taxonomy VL where VL.module_type = 'APP')
    SELECT  case when connect_by_isleaf = 1 then 0
                when level = 1             then 1
                else                           -1
           end as status,
    LEVEL,
    user_module_name as title,
    null as icon,
    ltrim(user_module_name, ' ') as value,
    null as tooltip,
    null as link
          FROM MODULES
          START WITH source_module_id = '1'
          CONNECT BY PRIOR source_module_id = target_module_id
    ORDER SIBLINGS BY user_module_name;
    

    In Oracle APEX, this gives a tree with the appropriate data, you can see here:

    https://Apex.Oracle.com/pls/Apex/f?p=32581:29 (username: guest, pw: app_1000);

    The SQL of the query results are:

    STATUSTITLE LEVELVALUE

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

    11 oracle FusionOracle Fusion
    -12 financial tablesFinancials
    -13 accounts payableAccounts payable
    04 APAP
    -1General Accounting 3General Accounting
    -14 GLGL
    05 GL_JE_CATEGORIESGL_JE_CATEGORIES
    05 GL_JE_SOURCES_TLGL_JE_SOURCES_TL
    02 human resourcesHuman resources

    The lowest level is the name of the table to level 5. HR is not any level under level 2, in the same way, "AP" (level 4) has nothing below, i.e. no level 5 and that's why I don't want to show these nodes. Is this possible with the above query?

    Thanks in advance for your suggestions!

    John

    Hello

    The following query will include only the nodes of level = 5 and their ancestors (or descendants):

    WITH modules LIKE

    (

    SELECT h.source_module_id

    b.user_module_name AS the title

    h.target_module_id

    To appl_taxonomy_hierarchy:

    appl_taxonomy_tl b

    appl_taxonomy vl

    WHERE h.source_module_id = b.module_id

    AND b.module_id = vl.module_id

    AND vl.module_type NOT IN ('PAGE', "LBA")

    UNION ALL

    SELECT DISTINCT

    table-name

    table_name

    , REGEXP_SUBSTR (table_name, ' [^ _] +')

    From the tables - required as a link between the TABLES and APPL_TAXONOMY

    UNION ALL

    SELECT module_key AS source_module_id

    AS user_module_name module_name

    module_id AS target_module_id

    Of appl_taxonomy vl

    WHERE vl.module_type = 'APP '.

    )

    connect_by_results AS

    (

    SELECT THE CHECK BOX

    WHEN CONNECT_BY_ISLEAF = 1 THEN 0

    WHEN LEVEL = 1 THEN 1

    OF ANOTHER-1

    The END as status

    LEVEL AS lvl

    title

    -, NULL AS icon

    , LTRIM (title, "") AS the value

    -, NULL as ToolTip

    -, Link AS NULL

    source_module_id

    SYS_CONNECT_BY_PATH (source_module_id - or something unique

    , ' ~' - or anything else that may occur in the unique key

    ) || ' ~' AS the path

    ROWNUM AS sort_key

    Modules

    START WITH source_module_id = '1'

    CONNECT BY PRIOR Source_module_id = target_module_id

    Brothers and SŒURS of ORDER BY title

    )

    SELECT the status, lvl, title, value

    -, icon, tooltip, link

    OF connect_by_results m

    WHEN THERE IS)

    SELECT 1

    OF connect_by_results

    WHERE the lvl = 5

    AND the path AS ' % ~' | m.source_module_id

    || '~%'

    )

    ORDER BY sort_key

    ;

    You may notice that subqueries modules and the connect_by_results are essentially what you've posted originally.  What was the main request is now called connect_by_results, and it has a couple of additional columns that are necessary in the new main request or the EXISTS subquery.

    However, I am suspicious of the 'magic number' 5.  Could you have a situation where the sheets you are interested in can be a different levels (for example, some level = 5 and then some, into another branch of the tree, at the LEVEL = 6, or 7 or 4)?  If so, post an example.  You have need of a Query of Yo-Yo, where you do a bottom-up CONNECT BY query to get the universe of interest, and then make a descendant CONNECT BY query on this set of results.

  • How to format better my query for a report?

    I have a shell script to run sql queries for the database information every day.

    However down here, I want some columns to be indented to the right and I also want to format the % column.

    As for column name, under the name of column, there are lines including one very long and longer line, how in a linesize?


    Checking information of State/DataGuard


    time of the error message
    Code CAL INSTALLATION GRAVITY DEST_ID MESSAGE number stamp
    ======================== ============= ========== ========== ========== === ========= ================================================================================================================================================================================================================================================================
    Thank you

    See the link for all the format patterns and items below... etc.

    http://docs.Oracle.com/CD/B19306_01/server.102/b14200/sql_elements004.htm

    Hope this helps,

    Concerning
    http://www.oracleracexpert.com
    Import and export transportable tablespace
    http://www.oracleracexpert.com/2009/09/transportable-tablespace-export-and.html
    Oracle pump export/import data with examples.
    http://www.oracleracexpert.com/2009/08/Oracle-data-pump-exportImport.html

  • How to write a SQL query?

    The employee list details empno, ename, job, DOB, retire_date. I want to
    Retirement date = dbo + 58 years... DOB display format 'dd-mon-yyyy' and retire_date 'MON-yyyy ".

    Published by: 1008586 on June 5, 2013 20:26

    Published by: 1008586 on June 5, 2013 20:30
    SELECT EMP_ID,
           emp_name,
           emp_dob,
           TO_CHAR (ADD_MONTHS (emp_dob, 58 * 12), 'MON-YYYY') emp_rtr_dt
      FROM employee;
    

    See you soon,.
    Manik.

  • How to write the query

    Hello

    How to write the sql query

    I have three type of table as

    1 table emp

    EMP_ID FIRST_NAME DEPT_ID

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

    1 kumar 10

    2 sam                          20

    3 30 damu

    2 table dept

    EMP_ID SALE_ID DEPT_ID

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

    1 101 10

    2 102 20

    3 103 30

    3. table sale

    EMP_ID SALE_ID SALE_AMT

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

    1 101 7

    2 102 8

    3 103 9

    I want the result as

    EMP_ID DEPT_ID SALE_AMT

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

    1                10                  7

    Thank you

    Are you looking for this?

    SELECT T1. EMP_ID,

    T1. DEPT_ID,

    W3M SALE_AMT

    FROM EMP T1,

    SALE T3

    WHERE T1. EMP_ID = T3. EMP_ID;

    OUTPUT:

    EMP_ID DEPT_ID SALE_AMT

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

    1         10          7

    2         20          8

    3         30          9

    If this is not the case, after the actual output, you need. Because that gives you the amount of sales deptwise

  • How to write a query for the given scenario?

    Hi all

    I have two tables EMP, DEPT with data below.
    EMP TABLE: -.
    SAL DEPID EMPLOYMENT ENAME EID
    111 RAM 1500 10 MANAGER
    222 SAM ASST MANAGER 2000 20
    KALA 333 2500 10 REGISTRAR
    444. BIMA 20 3000 MANAGER
    CHALA 555 MANAGER 3500 30
    RANI 666 ASST MANAGER 4000 10
    777 KAMAL MANAGER 2400 10

    DEPT TABLE: -.

    DEPID DNAME
    XX 10
    AA 20
    30 ZZ

    Q1: I want the sum of the salary of each Department and for the particular job. Here, in each Department manager, Assistant Manager, clerk positions are there.
    I want to display the result as below...
    10-20-30 JOBS
    --------------------------------------------------------------------------
    MANAGER OF 3900 3000 3500
    ASST MANAGER 4000 2000 NULL
    THE CLERK 2500 NULL NULL

    Please tell me how to write a sql query?

    Thank you
    SAI
    SQL> SELECT job,
      2         MAX(DECODE(deptno, 10, sum_sal)) "10",
      3         MAX(DECODE(deptno, 20, sum_sal)) "20",
      4         MAX(DECODE(deptno, 30, sum_sal)) "30"
      5  FROM (SELECT deptno, job, SUM(sal) sum_sal FROM emp GROUP BY deptno, job)
      6   GROUP BY job;
    
    JOB               10         20         30
    --------- ---------- ---------- ----------
    CLERK           1300       1900        950
    SALESMAN                              5600
    PRESIDENT       5000
    MANAGER         2450       2975       2850
    ANALYST                    6000
    
    SQL> 
    
  • How to write the query option in expdp

    Hi Please someone help me how to write the query option in expdp... .in expdp using the query option...

    where AM columnname between 5 May 12 02:57:00.000' and ' 02:59:59.999 6 May 12: ';


    Please do what is necessary...

    Pavan Kumar says:
    QUERY = (columnname scott.test: "where between 5 May 12 02:57:00.000 h ' and ' 6 May 12 AM 02:59:59.999'")

    Who will fail in databases, because you assume nls_date_format. How it is difficult to put to_date() surround channels? Rather than play with quotation marks, using one parfile thusly.

    query=table_owner.table_1:"where business_date between to_date('20120505025700 am','yyyymmddhhmiss am') and to_date('20120505025959 am','yyyymmddhhmiss am')"
    query=table_owner.table_2:"where business_date between to_date('20120505025700 am','yyyymmddhhmiss am') and to_date('20120505025959 am','yyyymmddhhmiss am')"
    query=table_owner.table_3:"where business_date between to_date('20120505025700 am','yyyymmddhhmiss am') and to_date('20120505025959 am','yyyymmddhhmiss am')"
    

    You do not have to have all the clauses in a single line, as they are side by side parfile, which would be enough. For this reason parfile is better than the command line in order to avoid all the back-citing dance.

  • How to write a query to return rows with the varchar column that contains even a single occurrence of the characters, such as Ÿ and

    How to write a query to return rows with the varchar column that contains even a single occurrence of the characters, such as Ÿ and

    I have a table whose columns with values such as

    MINNEAŸPOLIS and ¿VV ¿A

    Only the characters that are allowed in this column are alphabets, numbers, spaces, points and supports.

    Please help to write a SQL SELECT with Regexp_like query or any other option.

    Thanks to you all! Under query worked for me. Thank you Frank to explain the concept of hooks inside regexp_like.

    SELECT * FROM testspecial, WHERE REGEXP_LIKE (sampletext, "[^] ^ A - Z ^ a - z ^ 0-9 ^ [^.]") ^ {^} ^]') ;

  • How to write a simple select query to get the data of the table as an XML.

    How to write a simple select query to get the data of the table as an XML. In the query, I'm just adding items below which i need be there in the XML document
    select '<test_tag>'||EMP_NAME||'</test_tag>','<date>'||sysdate||'</date>' 
    from temp_table where id_num BETWEEN 1 AND 10;
    I have need to add the root tag as well in the beginning and the end of < root > < / root > this xml file. Please advice if this is possible with the select query
    without using XMLGEN, XMLQUERY or any other packages built and function?

    I need to URL escapes with the UTF-8 code points that we have already achieved using the utl_http package. Please help how to do that without using the utl_http package.

    What is wrong with him?

    At present, the only way I can think of to avoid a call to UTL_HTTP. SET_BODY_CHARSET is to write your own little wrapper.
    In this way, you can specify the Boolean parameter or omit it if you choose to use named parameters:

    SQL> create or replace function my_url_escape (url in varchar2)
      2  return varchar2
      3  deterministic
      4  is
      5  begin
      6   return utl_url.escape(url, false, 'AL32UTF8');
      7  end;
      8  /
    
    Function created
    
    SQL> select my_url_escape('http://some.uri.com/param?lang=fr&text=contrôle') from dual;
    
    MY_URL_ESCAPE('HTTP://SOME.URI
    --------------------------------------------------------------------------------
    http://some.uri.com/param?lang=fr&text=contr%C3%B4le
     
    
  • No idea how to write this query

    Hi, My Data is as below

    DocNum doc_date type of amount
    1154 15 November 11 232501.5 invoice
    200206 4 November 11 - 243672.64 credit memo
    Note flow 111 5 November 555.22 11

    Output must be

    DocNum doc_date amount Type AmountDR AmountCR
    1154 232501.5 15 November 11 Bill 232501.5
    Note credit 200206 4 November 11 - 243672.64 - 243672.64
    Note flow 111 5 November 555.22 11 555.22

    If the amount is > 0, then it must be displayed in the value of the amount to be AmountDR
    If amount < 0 then it must be displayed in the value of the sum amount CR



    Can help how to write this query
    with sample_table as (
                          select 1154 Docnum,date '2011-11-15' doc_date,232501.5 Amount,'Invoice' type from dual union all
                          select 200206,date '2011-11-04',-243672.64,'Credit Memo' from dual union all
                          select 111,date '2011-11-05',555.22,'Debit Memo' from dual
                         )
    select  Docnum,
            doc_date,
            Amount,
            type,
            case
              when Amount >= 0 then Amount
            end AmountDR,
            case
              when Amount < 0 then Amount
            end AmountCR
      from  sample_table
    /
    
        DOCNUM DOC_DATE      AMOUNT TYPE          AMOUNTDR   AMOUNTCR
    ---------- --------- ---------- ----------- ---------- ----------
          1154 15-NOV-11   232501.5 Invoice       232501.5
        200206 04-NOV-11 -243672.64 Credit Memo            -243672.64
           111 05-NOV-11     555.22 Debit Memo      555.22
    
    SQL> 
    

    SY.

  • How can I write the SQL query for this requirement?

    Hello

    I have a table that looks like this:

    NAME | ANNUAL |     VALUE
    ==== | ====== | =====
    execno |     480.     000004
    step |      480.     0400
    SCNA |     480. cd_demo
    System |     480.     D47-010
    type |     480.     step
    free_text |     480.     stage 400
    rbare |     480.     RBA-1
    execno |     482. 000004
    SCNA |     482. cd_demo
    System |     482.     D47-010
    free_text |     482.     step 300
    step |          482.          0300
    type |      482.     step
    rbare |     482.     RBA-1
    execno |     483.     000001
    type |     483.     step
    rbare |     483.     rke1
    SCNA |     483.     rke10
    step |     483.     0240

    Now, say that I want to fetch ONLY annual with execno = '000004' and '400' = step and scna = "cd_demo" and system = "d47-010' and type = 'step', how to write SQL code?
    At first, it seemed like a simple writing query but I've been struggling with it for hours without success. I must admit though that I'm not strong in SQL :-)
    There, can anyone help? Please...

    Thanks in advance.

    Emmanuel

    Published by: user12138559 on October 30, 2009 03:05

    Hi, Emmanuel.

    Welcome to the forum!

    Here's a way to do what you asked:

    SELECT       doc_id
    FROM       table_x
    GROUP BY  doc_id
    HAVING       SUM (CASE WHEN name = 'execno' AND value = '000004'  THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'step'   AND value = '400'     THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'scna'   AND value = 'cd_demo' THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'system' AND value = 'd47-010' THEN 1 END) > 0
    AND       SUM (CASE WHEN name = 'type'   AND value = 'step'    THEN 1 END) > 0
    ;
    

    If you think that a WHERE clause would be used, but WHERE does apply to a single line. You need a condition that checks several rows in the same group.
    WHEN has an effect something like WHERE.

    Published by: Frank Kulash, October 30, 2009 06:26

    This solution assumes that (name, annual) is unique.

  • How to write a query for the data exchange between two columns?

    How to write a query for the data exchange between two columns?

    I tried a request, does NOT work.
    update tmp t1 set t1.m1=t1.m2 and t1.m2=(select t2.m1 from tmp t2 where t2.student_id = t1.student_id)
    Thank you.

    Published by: user533361 on October 23, 2009 14:04

    Just plain and simple:

    update tmp t1
     set t1.m1=t1.m2,
         t1.m2=t1.m1
    /
    

    SY.

  • How to write to the system event log

    Windows 7 Home Premium 64-bit Service Pack 1

    I run a daily work to create an image of my drive system hard. Repeatedly the work began and, due to a material error, be abandoned. In some cases (mostly), this will result in the image of yesterday being destroyed, leaving me with no viable image in case I need to restore. Although the reader is old enough (3 years), I'm not want to replace it, because I know no other activity that has had a problem with it and diagnoses reported no problem.

    So I want to execute a batch file or a script before the regular daily system backup operation. The script would go to a SMART short self-test, and if no errors are reported, would signal the backup task to run. Conversely, if the self-test report any error, the script don't trigger not the backup task to run. I think I will need to write an entry in a kind of system event log, which would be defined in the trigger condition in the entrance to the Windows Task Scheduler for the backup task. If anyone can help with the details of how to write an entry to a log of system events?

    Or, perhaps, there is better way to achieve what I want to do?

    I guess that there is not a very high probability that the script will always truly detect a problem and prevent the last image of the destruction. But I tell myself that it is worth the effort.

    TIA

    Assuming that smartctl generates an errorlevel nonzero in case it failed, the following script will work, as long as Smartctl is run under the same account as Casper.

    I also made your script more transparent control setting. The if/then/else/if/then embedded instructions are perfect for computers, but are often misconstructed by the human mind. I'm a big believer in the KISS principle.

    OFF @echo
    FOR %%d Ko (% Date %) Today SET = %% A

    SET now = time %
    echo =.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.
    ECHO% now %%d now %%d %2
    echo"=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.=.
    Si (« %3 « == » »
    echo of the provided insufficient parameters
    output/b 1
    )

    IF/i %1 is goto short Action
    IF/i %1 is goto long Action
    ECHO 1 Parm [%1] is INVALID
    output/b 1

    : Action
    smartctl t %1 %2
    the echo of SECONDS to WAIT for selftest %3
    choice/n/t %3/d N
    smartctl-l selftest %2%

    Set Flag="%temp%\Smartctl.log".
    If exist % del % % flag flag
    If %ERRORLEVEL% is 0 echo. > Flag %

    For the handshake to work, you must place the CASPER command inside a file of commands as follows:

    off @echo

    If exist c:\Casper\Casper.exe '% temp%\Smartctl.log '.

Maybe you are looking for