SQL with conditions

Hello

I need to generate a summary table with conditions. Here are the details:

create the table tb_class (classId number (5), studentNum number (5));

create table tb_grade (classId number (5), gradeNum number (5)):

insert into table values tb_class (101, 100);

insert into table values (201, 102) tb_class;

insert into table values (102, 103) tb_class;

insert into table values tb_grade (101, 1);

insert into table values (102, 1) tb_grade;

insert into table values (201, 2) tb_gradfe;

I would like to get the total number of students registed in a specific shade with a SQL, the result is expected as follows:

GradeNum studentNumRegistered studentNumNonRegisted

1                         203                                      102

2                         102                                      203

Is that what you are looking for?

WITH subsum AS
 (SELECT tb_grade.gradenum,
         SUM(tb_class.studentnum) AS students
  FROM   tb_class
  JOIN   tb_grade ON tb_grade.classid = tb_class.classid
  GROUP  BY tb_grade.gradenum)
SELECT subsum.gradenum,
       SUM(subsum.students) AS studentnumregistered,
       SUM(subsum1.students) AS studentnumnonregistered
FROM subsum
JOIN subsum subsum1 ON subsum1.gradenum != subsum.gradenum
GROUP  BY subsum.gradenum;

Tags: Database

Similar Questions

  • join with condition

    Hi all

    Is there a possible way to cross the join with condition?

    I want something like this:

    Table A: custid, accu_id, sum

    CustID, accu_id unique =

    CustomerID amount accu_id

    10 25 400

    10 35 447

    10 29 420

    20 30 510

    30 35 472

    .

    .

    .

    Table b: accu_id, description

    accu_id description

    shoes 25

    Book 29

    30 computer

    pen 35

    Note: in table A, it is a mismatch of the accu_id values that do not use. Please, take into account this.

    I want to see all the columns in the TABLE B for each custid in A. TABLE (something like cross join but with ONE article.) The following query does not work.

    Select * from a right join B on A.accu_id = B.accu_id;

    10-25

    10-29

    10-30

    10-35

    20-25

    20-29

    20-30

    20-35

    30 25

    30 29

    30 30

    30-35

    What should I do for this?

    Thanks in advance

    Use partition outer join:

    with a (too)

    Select double union all 10 custid, accu_id 25, amount 400

    Select 10,35,447 from all the double union

    Select 10,29,420 from all the double union

    Select 20,30,510 from all the double union

    Select double 30,35,472

    ),

    b like)

    Select accu_id 25, "shoe" description of all the double union

    Select 29, 'book' from dual union all

    Select 30, 'computer' from dual union all

    Select 35, 'pen' from dual

    )

    Select a.custid,

    a.accu_id,

    a.amount,

    b.

    a

    by (a.custid) partition

    right join

    b

    On a.accu_id = b.accu_id

    order of a.custid,

    a.accu_id

    /

    AMOUNT ACCU_ID CUSTID DESCRIPT
    ---------- ---------- ---------- --------
    10 25 400 shoe
    10 29 420 book
    10 35 447 pen
    10 computer
    20 30 510 computer
    shoe 20
    book 20
    20                       pen
    30 35 472 pen
    30 shoe
    30 book

    AMOUNT ACCU_ID CUSTID DESCRIPT
    ---------- ---------- ---------- --------
    30 computer

    12 selected lines.

    SQL >

    SY.

  • Where to write the condition in the design of workflows with conditional step?


    Hello

    Again, I wish BP and workflow with contitional design stage.

    I had designed BP and workflow.

    As directed by the user for Udesigner guide, I had added trigger before the condition step.

    But I do not understand where to set the Condition to test?

    If I need to write the condition in triggering elemt itsel... How to proceed?

    for example, I want to write the condition as cost of Tota > = 100000, it must follow a path and if fails to another path.

    The conditions of triggers are specified in the workflow settings.  After you have created a new configuration, open it and click on the settings tab.  You will see a tree structure of the workflow with conditional branches.  Click a conditional branch to set the parameters for the trigger for this route condition.

  • Reactive layouts: publish multiple Sites with conditional Builds and which connect

    I hope that someone can provide a simple solution to publish problems I've had with adapted presentations when you try to publish several sites with conditional builds. Essentially, I want to be able to have an index page that links to one of the two variants of the published sites that I called 'General' and 'specific '. When I click on the 'general' link I want to not open the site which was published with a conditional for all these subjects compilation labeled as 'general' and when I click on the 'link' want it to open the site which was published using a conditional version for 'specific '.

    Here are the steps I took to create sites and can't seem to get to bind correctly:

    Table of contents, topic Creation and tagging content

    1. Creates a Table of contents.
    2. Added 2 topics in the Table of contents. The first topic, I called "general" and the second issue I called, 'specific '.
    3. I then click with the right button on the "general" and selected subject Tag to build conditional apply. From there, I've created a new tag called "General".
    4. I repeated this process to create the specific tag, but do a right-click on the 'specific' theme and the creation of a new tag called "specific".

    Layouts reactive and edited the sites based on the conditional tags

    1. Created sensitive presentation using the standard layout and content generated without any conditional builds.
    2. Duplicated sensitive put in page and gave him the content of 'general' then it is generated using the conditional, "General" version If the finished publication published content has shown that the 'general' subject, as expected.
    3. I then repeated the same process for the specific content and content using the version parole, generated 'specific '. When over content published showed that the subject marked as 'specific' as expected.

    Added an Index page to the table of contents

    1. Created a new topic to serve as the launch page.
    2. Added a 'general' hyperlink called for the launch of the general "theme found in the general publishes from the resource manager.
    3. Added a hyperlink called 'specific' to the launch of the general "theme found in the specific issues from the resource manager.
    4. I then republish the sensitive standard layout site.

    From this point, it gets stuck and won't open properly published Web sites. I don't know why it won't launch hyperlinks correctly. Is there something I'm missing? Let me know if you do not want to see my files. I will be gladly their.

    OK, thanks a lot for the capture screen. They help more than you realize.

    So here's one of the biggest mistakes I think that you have done so far. You use the resource manager to link to published results. If it is technically possible to do, I'm pretty sure Adobe never planned for it to be used this way.

    It may help to think in terms of creation of food products. I have long considered as RoboHelp to be very much like working in my kitchen. All consumables (heading text in the headings, images, HTML pages, etc.) are just as raw ingredients. (Eggs, milk, flour, etc.). The places of storage (hard drive) it's like the pantry and the fridge. And RoboHelp provides facilities to easily combine ingredients to create the different recipes.

    This next bit will be somewhat exaggerated, but bear with me. Maybe you have one or more neighbors and all you want to share some common "ingredients". If you set the things where each of you have access to a wine cellar and a shared refrigerator. Maybe you do a Dutch sauce killer. You create it and place in the refrigerator, then your other participants have access through the common "fridge". This is exactly what the resource manager is intended to help.

    Now assume that you create something like cookies chocolate chip and you keep in the refrigerator. Well, that's fine, but you don't want to use cookies to chocolate chip already baked in a recipe that might call for cookie dough. But that's what happens when you take an exit and place in a place intended for raw ingredients. And you will see the strange behavior. Prepare for these cookies chemically changes them so that cookies already are significantly different from the dough used to create them. Similarly, you don't want to take one or more output files and reuse in a project source.

    So in your case, you run an index file and that fires events to produce the output. All should be well. But when you click on the links to open topics, topics are intended to show up more in the right panel. Think of the picture of how works of image on a TV. The moment that link you to something intended to fill the screen, he is forced into this smaller area on the right. If you end up with what you see in the last picture.

    I suggest the following steps.

    First, REMOVE your resource manager exits.

    REMOVE all links that can point here.

    Output records where people will consume copy your projects. (The web server)

    Then figure either the parent (.. /.. / somefolder/somefile.htm) path to other systems or the absolute path (http://www.whatever.com) and to link the projects in this way.

    Sorry, but without seeing the installation of first hand, it is difficult to say what should be these paths.

    I hope this was helpful... Rick

  • How to avoid duplicates on a column with condition

    Hi all

    I need some advice here. At work, we have an Oracle APEX application that allow the user to add new records with the decision of the increment automatic number based on the year and the group name.

    Said that if they add the first record, group name AA, for 2012, they get the decision number AA 1 2013 as their record casein displayed page of the report.

    The second record of AA in 2013 will be AA 2 2013.

    If we add about 20 records, it will be AA 20 2013.

    The first record for 2014 will be AA 1 2014.

    However, recently, we get a claim of the user on two files of the same name of group have the same number of the decision.

    When I looked in the history table and find that the time gap between 2 record is about 0.1 seconds.

    In addition, we have the correspondence table which allows the user admin update the sequence number start with the restraint that it must be greater than the maximum number of the current name of the current year.

    This boot sequence number and the name of the group is stored together in a table.

    And in some other case, the user can add a decision duplicate for related record number. (this is a new feature)

    The current logic of the procedure to add the new record on the application are

    _Get max record table with selected group name (decision_number) and the current year.

    _INSERT in the folder table the new record came with the decision to number + 1

    _ update sequence number of the number of the decision just added.

    So instead of utitlising the process of editing the built-in automatic table of the APEX, I write a procedure that combine all three processes.

    I have run some loop for continually perform this procedure, and it seems that it can generate autotically new decision unique number with time about 0.1 second difference.

    However, when I increase the number of entry to 200 and let two users run 100 each.

    If the time gap is about 0.01 second, double decision numbers are displayed.

    What can I do to prevent duplicate?

    I can't just apply a unique constraint here for three columns with condition because it can be duplicated in some special conditions. I don't know much about the use of lock and its impact.

    This is the content of my procedure

    create or replace

    PROCEDURE add_new_case)

    -ID just use the trigger

    p_case_title IN varchar2,

    p_year IN varchar2,

    p_group_name IN VARCHAR2,

    -decisionnumber here

    p_case_file_number IN VARCHAR2,

    -active

    p_user in VARCHAR2

    )

    AS

    NUMBER default_value;

    caseCount NUMBER;

    seqNumber NUMBER;

    previousDecisionNumber NUMBER;

    BEGIN

    -execution immediate q '[alter session set nls_date_format = "dd/mm/yyyy"]';

    SELECT count (*)

    IN caseCount

    OF CASE_RECORD

    WHERE GROUP_ABBR = p_group_name

    AND to_number (to_char (create_date, "yyyy")) = to_number (to_char (date_utils.get_current_date, "yyyy"));

    SELECT max (decision_number)

    IN previousDecisionNumber

    OF CASE_RECORD

    WHERE GROUP_ABBR = p_group_name

    AND to_number (to_char (create_date, "yyyy")) = to_number (to_char (date_utils.get_current_date, "yyyy"));

    IF p_group_name IS NULL

    THEN seqNumber: = 0;

    ON THE OTHER

    SELECT Seq_number INTO seqNumber FROM GROUP_LOOKUP WHERE ABBREVIATION = p_group_name;

    END IF;

    IF caseCount > 0 THEN

    default_value: largest = (seqNumber, previousdecisionnumber) + 1;

    ON THE OTHER

    default_value: = 1;

    END IF;

    INSERT INTO CASE_RECORD (case_title, decision_year, GROUP_ABBR, decision_number, case_file_number, active_yn, created_by, create_date)

    VALUES (p_case_title, p_year, p_group_name, default_value, p_case_file_number, 'Y', p_user, sysdate);

    -Need to update the sequence here also

    UPDATE GROUP_LOOKUP

    SET SEQ_NUMBER = default_value

    WHERE the ABBREVIATION = p_group_name;

    COMMIT;

    EXCEPTION

    WHILE OTHERS THEN

    Logger.Error (p_message_text = > SQLERRM)

    , p_message_code = > SQLCODE

    , p_stack_trace = > dbms_utility.format_error_backtrace

    );

    LIFT;

    END;

    Many thanks in advance,

    Ann

    It's easier to solve for the case, while p_group_name is not null. In this case, you update a GROUP_LOOKUP line, so that you can select to update this line at the beginning, to prevent cases of two for the same group added at the same time. To do this, change the selection of GROUP_LOOKUP to:

    SELECT Seq_number INTO seqNumber FROM GROUP_LOOKUP WHERE ABBREVIATION = p_group_name for an updated VERSION OF the SEQ_NUMBER;

    and move this to be the first thing that did the procedure - before it has CASE_RECORD lines.

    In the case when p_group_name is set to null, you have some object to be locked. I think the best you can do is to lock the entire table GROUP_LOOKUP:

    the table lock in exclusive mode GROUP_LOOKUP wait 100;

    The '100 expectation' means that he will wait until 100 seconds before giving up and trigger an error. in practice, that is expected to only wait a moment.

    Exclusive mode allows others to read, but not to update the table.

    UPDATES and the LOCK of the TABLE will be updates of other sessions wait for this transaction to validate. Queries from other sessions are not affected.

    The locks are released when you commit or roll back.

  • XMLTable to extract columns with conditional path does not

    Hello

    I am on 11.2.0.3 and I need to extract columns on a section of XML with conditions on, but I get "ORA-00907: lack the right parenthesis", so I think that the way I go about it is not supported or that I have somehow the wrong syntax or something.

    This is a very simplified what I'm trying to do (there could be several different entries in the < sets1 > and < sets2 > sections and they might be in different orders, is not as if I can always choose the first or the last):

    with sample_data as (select 1 id,
                                xmltype('<root>
                                           <sets1>
                                             <set1><set_name>name1</set_name><set_val>val1</set_val></set1>
                                             <set1><set_name>name2</set_name><set_val>val2</set_val></set1>
                                           </sets1>
                                           <sets2>
                                             <set2><set_name>name3</set_name><set_val>val3</set_val></set2>
                                             <set2><set_name>name4</set_name><set_val>val4</set_val></set2>
                                           </sets2>
                                         </root>') xml_doc from dual)
    select *
    from   sample_data sd,
           xmltable('<root>' passing sd.xml_doc
                    columns col1 varchar2(10) path 'sets1/set1[set_name=''name1'']/set_val',
                            col2 varchar2(10) path 'sets1/set1[set_name=''name2'']/set_val',
                            col3 varchar2(10) path 'sets2/set2[set_name=''name4'']/set_val') x;
    

    What I'm trying to get:

    COL1  COL2  COL3
    ----  ----  ----
    val1  val2  val4
    

    I know that I could separate the < set1 > and < set2 > nodes in their own xmltypes xmltable on it and then join them and make the necessary pivoting, etc., but when I try to start that against only 1000 lines, db do not love and ended my session! Therefore, I'm looking for a more elegant way to do it.

    Is there a way to do this in a XMLTABLE? Pointers are very welcome!

    It solves your problem of sample request and you get the output that show you.

     with sample_data as (select 1 id,
                                 xmltype('
                                            
                                              name1val1
                                              name2val2
                                            
                                            
                                              name3val3
                                              name4val4
                                            
                                          ') xml_doc from dual)
     select x.*  -- change
     from   sample_data sd,
            xmltable('/root' passing sd.xml_doc  -- change
                     columns col1 varchar2(10) path 'sets1/set1[set_name="name1"]/set_val',  -- change
                             col2 varchar2(10) path 'sets1/set1[set_name="name2"]/set_val',  -- change
                             col3 varchar2(10) path 'sets2/set2[set_name="name4"]/set_val') x;  -- change
    

    As you can see, I've marked the lines that I've changed.  The error you saw came to use two single quotes in the COLUMN XPath instead to use double quotes.  Then I changed the XPath expression in the XMLTable brackets as well.

    I'm confused on what the columns you really want overall, in terms of how you know which values you want, or did you mean that you want something random sets1 and sets2.

    You store the XML file in a column of XMLType SECUREFILE BINARY, right?  It seems that you made previous visits, but just double check.

  • How can I write a sql with a Union.

    How can I write a sql with a Union.


    Select emp_name, emp_no, emp_sal of the emp


    If show_Less_100000 = "Yes" then emp_sal < 100000 (all values less than 100000)

    otherwise the full list.



    Thank you
    Harsha

    Published by: taty on July 31, 2012 11:28
    SQL> variable show_Less_100000 varchar2(3)
    SQL> exec :show_Less_100000 := 'Yes';
    
    PL/SQL procedure successfully completed.
    
    SQL> select  ename,
      2          empno,
      3          sal
      4    from  emp
      5    where (
      6               :show_Less_100000 = 'Yes'
      7           and
      8               sal < 2000
      9          )
     10       or nvl(:show_Less_100000,'No') != 'Yes'
     11  /
    
    ENAME           EMPNO        SAL
    ---------- ---------- ----------
    SMITH            7369        800
    ALLEN            7499       1600
    WARD             7521       1250
    MARTIN           7654       1250
    TURNER           7844       1500
    ADAMS            7876       1100
    JAMES            7900        950
    MILLER           7934       1300
    
    8 rows selected.
    
    SQL> exec :show_Less_100000 := 'All';
    
    PL/SQL procedure successfully completed.
    
    SQL> select  ename,
      2          empno,
      3          sal
      4    from  emp
      5    where (
      6               :show_Less_100000 = 'Yes'
      7           and
      8               sal < 3000
      9          )
     10       or nvl(:show_Less_100000,'No') != 'Yes'
     11  /
    
    ENAME           EMPNO        SAL
    ---------- ---------- ----------
    SMITH            7369        800
    ALLEN            7499       1600
    WARD             7521       1250
    JONES            7566       2975
    MARTIN           7654       1250
    BLAKE            7698       2850
    CLARK            7782       2450
    SCOTT            7788       3000
    KING             7839       5000
    TURNER           7844       1500
    ADAMS            7876       1100
    
    ENAME           EMPNO        SAL
    ---------- ---------- ----------
    JAMES            7900        950
    FORD             7902       3000
    MILLER           7934       1300
    
    14 rows selected.
    
    SQL> 
    

    SY.

  • How to use Bulk collect in dynamic SQL with the example below:

    My Question is

    Using of dynamic SQL with collection in bulkif we pass the name of the table as "to the parameter' function, I want to display those

    An array of column names without vowels (replace the vowels by spaces or remove vowels and display).

    Please explain for example.

    Thank you!!

    It's just a predefined type

    SQL> desc sys.OdciVarchar2List
     sys.OdciVarchar2List VARRAY(32767) OF VARCHAR2(4000)
    

    You can just as easily declare your own collection type (and you are probably better served declaring your own type of readability if nothing else)

    SQL> ed
    Wrote file afiedt.buf
    
      1  CREATE OR REPLACE
      2     PROCEDURE TBL_COLS_NO_VOWELS(
      3                                  p_owner VARCHAR2,
      4                                  p_tbl   VARCHAR2
      5                                 )
      6  IS
      7     TYPE vc2_tbl IS TABLE OF varchar2(4000);
      8     v_col_list vc2_tbl ;
      9  BEGIN
     10      EXECUTE IMMEDIATE 'SELECT COLUMN_NAME FROM DBA_TAB_COLUMNS WHERE OWNER = :1 AND TABLE_NAME = :2 ORDER BY COLUMN_ID'
     11         BULK COLLECT
     12         INTO v_col_list
     13        USING p_owner,
     14              p_tbl;
     15      FOR v_i IN 1..v_col_list.COUNT LOOP
     16        DBMS_OUTPUT.PUT_LINE(TRANSLATE(v_col_list(v_i),'1AEIOU','1'));
     17      END LOOP;
     18*  END;
    SQL> /
    
    Procedure created.
    
    SQL> exec tbl_cols_no_vowels( 'SCOTT', 'EMP' );
    MPN
    NM
    JB
    MGR
    HRDT
    SL
    CMM
    DPTN
    
    PL/SQL procedure successfully completed.
    

    Justin

  • Calculation of the sum with condition

    Hello
    I start with BI publisher, and I want to take a NAP with condition.

    My report output XLS, I haves columns, named ACCOUNT_TYPE and TREE_NODE and MOENTARY_AMOUNT_03 that are my PS query fields

    I want to sum only when a condition is true.

    <? xdofx:If ACCOUNT_TYPE = 'R' AND TREE_NOD = 'TEST' then
    Sum (MONETARY_AMOUNT_03)
    end if? >

    This does not,
    could you help me?

    thaks!

    You should do this:

  • Conversion with conditional text in table

    I take the first steps in converting unstructured structure image. A single document is fairly clean except for one question: my structure breaks around conditional text in tables. (The tables have a their own, but the conditional text questions f3ew seems to make the problem worse) I don't know how it should be treated. Structure tags are displayed in the view below.

    condTable.png

    And here's the view of the Structure:

    TblStruct.png

    Is this something that can be implemented with a qualifier, and if so, how? In addition, in the mapping of conversion table, is there any dependency order, as well, on which appears the conditional text element?

    Martine

    As Michael says, a conversion table does not convert the structure conditions. In a structured document, we apply, removes, shows and hides the conditions in the same way as is done on an informal document. The only difference is that you can select entire items and treat them with conditions.

    In a sense, FrameMaker treats conditions like processing instructions. If you need to export a document structured in XML and view it with a browser or a text editor, you can find instructions for treatment that punctuate the beaches of conditional text.

    So, once again as Michael, the text says conditional is not breaking your structure. It is superimposed on the structure.

    Van

  • Encoded text with conditional compilation still tags appear in TOC even if the label is "excluded".

    I use TCS2, Windows XP.

    After you have created a book in FM and coding with conditional compilation tags, I imported HR. When I generate, I output the value tag:

    NOT NoOUtput AND NOT internal AND NOT printed - I want to generate my external, webhelp online help. And it works like a charm. Except that:

    • In the table of contents, I can still see the stars for the things that are "internal" - when I click on it, they're not going anywhere... but I don't want them to appear in the table of contents!

    It seems to exclude from the index and search. I don't know that miss me just a step, or something...


    Browsing the forums I found this... http://forums.Adobe.com/message/751847#751847 -I don't know if it is still applicable, because it seems to allude to RH6 (which is a bit far from the 8 HR that I use)...

    Any help is appreciated!

    TIA,

    Adriana

    @Daggins - that's what I was talking about! I knew it was there somewhere ;>)

    @adrianaharper - if it doesn't work properly in PDF files that you create on the FM band; what the TOC looks like FM? You're just pulling in HR when you import/link right? If the faulty internal topics are appearing in the table of contents of the FM, then expect them to appear in HR too. You must kill them, FM or kill them in HR.

  • Optimize SQL with case-when-other

    Hello

    try to categorize DateValue into 3 groups
    1. effective: current month
    2. for a YEAR: between January and last month of the current year
    3. for a YEAR: between January and last month of the last year

    I have a feeling that my SQL could be much shorter and faster. I would be grateful for professional advice...

    -case when TO_NUMBER ((TO_CHAR (DOCUMENT_TIMESTAMP, 'YYYY') |)) To_char (DOCUMENT_TIMESTAMP, 'MM'))) = TO_NUMBER (TO_CHAR (sysdate, 'YYYY') |) To_char (sysdate, 'MM'))
    can 'real '.
    -FOR A YEAR
    When TO_NUMBER ((TO_CHAR (DOCUMENT_TIMESTAMP, 'YYYY') |)) To_char (DOCUMENT_TIMESTAMP, 'MM'))) between TO_NUMBER (TO_CHAR (sysdate, 'YYYY') |) (' 01') and TO_NUMBER (TO_CHAR (sysdate, 'YYYY') |) To_char (sysdate, 'MM'))-1
    then "CDA".
    -PYTD
    When TO_NUMBER ((TO_CHAR (DOCUMENT_TIMESTAMP, 'YYYY') |)) To_char (DOCUMENT_TIMESTAMP, 'MM'))) between TO_NUMBER (TO_CHAR(sysdate, 'YYYY')-1). ' 01' and TO_NUMBER (TO_CHAR(sysdate, 'YYYY')-1 |) To_char (sysdate, 'MM'))-1
    then "PYTD".
    else "Others" end up as ABC

    Hello

    I find trunc to be more readable:

    SQL> WITH DATA AS (
      2     SELECT SYSDATE d FROM dual UNION ALL
      3     SELECT add_months(SYSDATE, -12) FROM dual UNION ALL
      4     SELECT DATE '2009-01-01' FROM dual
      5  )
      6  SELECT to_char(d, 'dd-mon-yyyy') "Date",
      7         CASE
      8            WHEN trunc(d, 'month') = trunc(SYSDATE, 'month') THEN
      9             'Actual'
     10            WHEN trunc(d, 'year') = trunc(SYSDATE, 'year') AND d < sysdate THEN
     11             'YTD'
     12            WHEN trunc(d, 'year') = add_months(trunc(SYSDATE, 'year'), -12) THEN
     13             'PYTD'
     14         END "Case"
     15    FROM DATA
     16  ;
    
    Date              Case
    ----------------- ------
    10-jun-2009       Actual
    10-jun-2008       PYTD
    01-jan-2009       YTD
    

    Kind regards

    --
    Vincent

    Published by: user11163377 on June 10, 2009 02:12 - corrected the CDA column

  • Release of SQL with the conditional basis

    Hi guys,.

    I have a NAICS_CODE table that contains two passes and data are as below

    NAICS_CODE NAICS_DESC
    321113 Mills
    32111-sawmills and wood PreservationT
    3211 sawmills and wood PreservationT
    321 ManufacturingT wooden products
    32 manufacturing


    I run a sql query which will check if there is NAICS_CODE = 321113, then it will retrun

    321113
    32111
    3211
    12 s
    32
    Otherwise, it will return nothing


    I framed a query like this

    SELECT NCMI1. NAICS_CODE,
    NCMI1. NAICS_DESC,
    NCMI1. INHERIT_PROPS
    OF NAICS_CODE NCMI1
    WHERE (SELECT COUNT (1) OF NAICS_CODE WHERE NAICS_CODE = '321113') > = 1
    AND)
    NAICS_CODE = '321113'
    OR NAICS_CODE = '32111'
    OR NAICS_CODE = "3211.
    OR NAICS_CODE = '321'
    OR NAICS_CODE = '32')

    ORDER BY Length (NAICS_CODE) DESC

    I was wondering is there a better way to do this.

    Please five any suggestion, thanks in advance

    I am using oracle 11g
    with testdata as (
    select 321113 NAICS_CODE, 'Sawmills' NAICS_DESC from dual union all
    select 32111, 'Sawmills and Wood PreservationT' from dual union all
    select 3211, 'Sawmills and Wood PreservationT' from dual union all
    select 321, 'Wood Product ManufacturingT' from dual union all
    select 32, 'Manufacturing' from dual
    )
    
    select NAICS_CODE from testdata
    start with NAICS_CODE = 321113
    connect by nocycle
    NAICS_CODE = prior substr(NAICS_CODE, 1, length(NAICS_CODE) - 1)
    
    NAICS_CODE
    321113
    32111
    3211
    321
    32 
    
  • Query SQL Report with condition (multiple settings) at the point of the apex?

    Hi all

    I have a small problem and cannot find a solution.

    I need to create reports based on a query, SQL or I.R. Nothing hard here.
    I need to add the WHERE clause dynamically with javascript to an element of the Apex.
    Even once is not very difficult. I set the agenda of the Summit, put my query like this "SELECT * FROM MYTAB WHERE COL1 =: P1_SEARCH" then I call the page by setting the P1_SEARCH value. For example, COL1 is rowid. It works very well.

    But here's my problem. Consider that P1_SEARCH contains several ROWID, and I don't know the number of these values,
    (no I don't create a large number of items and create a query with so much GOLD!), I would sotheming like "SELECT * FROM MYTAB WHERE ROWID IN (: P1_SEARCH) with something like: ROWID1, ROWID2 in P1_SEARCH."

    I also tried: 'ROWID1, ROWID2' and 'ROWID1', 'ROWID2 '.
    but I can't get anything else than the mistake of filter. It works with a value, but as soon as there are two values or more, it seems that the Apex is unable to read the string.


    How can I do it please?

    Thanks for your help.

    Max

    mnoscars wrote:

    But here's my problem. Consider that P1_SEARCH contains several ROWID, and I don't know the number of these values,
    (no I don't create a large number of items and create a query with so much GOLD!), I would sotheming like "SELECT * FROM MYTAB WHERE ROWID IN (: P1_SEARCH) with something like: ROWID1, ROWID2 in P1_SEARCH."

    I also tried: 'ROWID1, ROWID2' and 'ROWID1', 'ROWID2 '.
    but I can't get anything else than the mistake of filter. It works with a value, but as soon as there are two values or more, it seems that the Apex is unable to read the string.

    For a standard report, see + {message identifier: = 9609120} +.

    For an IR - and improve safety by avoiding the risk of SQL Injection, use a collection containing the values in a column instead of a CSV list:
    {code}
    SELECT * FROM MYTAB WHERE ROWID IN (SELECT c001 FROM apex_collections WHERE collection_name = "P1_SEARCH")
    {code}
    (Please close duplicate threads spawned by your original question.)

  • Run the query in accordance with condition

    Oracle 10g version

    Hi gurus

    I have the following data

    Examples of data

    SELECT DeptNo FROM scott.emp

    UNION ALL

    SELECT EmpNo FROM scott.emp

    ;

    Now what I want is I want to execute conditionally of those surveyed, something like below:

    If list_item = 'I', then run below

    SELECT DeptNo FROM scott.emp

    otherwise run below

    SELECT EmpNo FROM scott.emp

    End if;

    ------

    I want to keep the union all and run the query under the terms...

    Set a long tank (max 4000)

    L_WHERE_CLAUSE

    Use it in your application as a substitution variable by prefixing with &

    WHERE & L_WHERE_CLAUSE

    Assign the value into a pl/sql block (trigger, formula column)

    IF condition THEN

    L_WHERE_CLAUSE: = '1 = 1';

    ON THE OTHER

    L_WHERE_CLAUSE: = '1 = 2';

    END IF;

    Now, among the options that have been suggested to you and the information you provided, I think the solution of Solomon should be easier. Just refer to the column list_item has a link within your query variable (assuming that this and the query where list_item belongs are related, for example, there is a join between them)

    SELECT DeptNo FROM scott.emp, t

    WHERE: list_item = 'l '.

    UNION ALL

    SELECT EmpNo FROM scott.emp, t

    WHERE nvl(:list_item,'x')! = « l »

Maybe you are looking for