XQuery with Union

As I am not able to use IF-ELSE in Oracle for select statements, I use to get rid of a select set of query results and UNION to get the results of other queries set according to the value of the parameter.

Example of a normal query:

Select FNAME LNAME from EMP where Param.1 in ('NAME', 'NAME')

UNION

SELECT CITY, ADDRESS from EMP where Param.1 in ('LOCATION', 'ADDRESS')

When I give Param.1 as 'NAME', it gives me the results of the first query set while it ignores another query resultset will null coz Param.1 isn't in "Position" or "ADDRESS".

Same Wau if I give Param.1 'Address', this is for me the result set of a query resultset 1 2nd query and spread as it is null.

But the same approach doesnot work to query Oracle with Xquery that follows:

Select rtrim (XMLELEMENT ("lines", XMLAGG (RW.column_value)), ',') stopped
EMPTABLE UL, XMLTABLE (' sets of lines/lines/lines ' UL of PASSAGE. ") TEXT) AS RW

WHERE

[Param.1] IN ('NAME', 'NAME')

UNION

Select rtrim (XMLELEMENT ("lines", XMLAGG (RW.column_value)), ',') stopped
ADDRESSTABLE UL, XMLTABLE (' sets of lines/lines/lines ' UL of PASSAGE. ") TEXT) AS RW

WHERE

[Param.1] IN ('LOCATION', 'ADDRESS')


Here, if the Param.1 is "NAME" then the results in the form < all > < / lines > + out of another query (that thing I want)

How can I remove this < Rowset > < / lines > output?

As I am not able to use IF-ELSE in Oracle for select statements

How about a CASE statement?
If every query is always supposed to return only a single grouped column (and of course a single line), you can use this:

SELECT CASE WHEN param_1 IN ('VAL1', 'VAL2')
             THEN (
               SELECT ...
               FROM emptable, XMLTable( ... )
             )
            WHEN param_1 IN ('VAL3', 'VAL4')
             THEN (
               SELECT ...
               FROM addresstable, XMLTable( ... )
             )
        END AS Orders
FROM dual;

If you prefer that the approach of the UNION, then:

Here, if the Param.1 is 'NAME' then results such as + out of another query (that thing I want)

It is because of the aggregation XMLAgg function.
An aggregate without GROUP BY function always returns a line, even if there is no line in the original game.

SQL> SELECT XMLElement("Rowset", XMLAgg(rw.column_value))
  2  FROM emptable ul
  3     , XMLTable('/Rowsets/Rowset/Row' passing ul.text) as rw
  4  WHERE 1 = 0
  5  ;

XMLELEMENT("ROWSET",XMLAGG(RW.
--------------------------------------------------------------------------------

 

You can group into an empty list of column to force the required behavior:

SQL> SELECT XMLElement("Rowset", XMLAgg(rw.column_value))
  2  FROM emptable ul
  3     , XMLTable('/Rowsets/Rowset/Row' passing ul.text) as rw
  4  WHERE 1 = 0
  5  GROUP BY ()
  6  ;

XMLELEMENT("ROWSET",XMLAGG(RW.
--------------------------------------------------------------------------------
 

You must also use UNION ALL instead of UNION whereas Oracle doesn't bother doing the a unnecessary sort operation.

What is the purpose of RTRIM in your examples? I see no reason to call it on an instance of XMLType, in addition, it performs a type conversion from implicit VARCHAR2 data that can potentially cause errors.
If you must serialize the resulting XMLType column and then use the methods getStringVal(), getClobVal(), or XMLSerialize (11g).

Published by: odie_63 on 7 nov. 2012 23:24

Tags: Oracle Development

Similar Questions

  • Reg: Query with UNION

    Dear all,

    I have two tables

    TABLE A (A_DATE, COLA1, COLA2)

    TABLE B (B_DATE)

    A_DATE = B_DATE

    Examples of tables:

    TABLE A (11 selected lines)

    A_DATE COLA1 COLA2
    03/01/201354VAL76
    04/01/201311VAL78
    04/01/201311VAL22
    04/01/201374VAL22
    04/02/201315VAL45
    04/02/201311VAL22
    04/03/201344VAL22
    04/03/201371VAL73
    04/04/201399VAL13
    04/05/201311VAL22
    04/05/201311VAL23

    TABLE B (01 April-30 April)

    B_DATE
    04/01/2013
    04/02/2013
    04/03/2013
    04/04/2013

    (condition 1: month: April)

    AND

    condition 2: CALA1-> 11

    AND

    condition 3: COLA2-> VAL22)

    I need to display all records for the months April to TABLE A,.

    If the documents are not present in TABLE A for every 30 days, I need to display null, by reading DATE information in TABLE B

    Expected results (sample)

    Date COLA1 COLA2
    04/01/201311VAL22
    04/02/201311VAL22
    04/03/2013
    04/04/2013
    04/05/201311VAL22

    Currently I have the following query

    Select A_DATE, COLA1, COLA2 from TABLEA

    where COLA1 = 11 and COLA2 in ('VAL22') and A_DATE between ' 2013-04-01 00:00:00.0' AND ' 00:00:00.0' 2013-04-30

    Union of all the

    Select B_DATE, null, null from TABLEB if date between ' 2013 - 04 - 01 00:00:00.0' AND ' 00:00:00.0' 2013-04-30

    But I'm the duplicate records for the values in TABLE a.

    Output current (sample)

    Date COLA1 COLA2
    04/01/201311VAL22
    04/01/2013
    04/02/201311VAL22
    04/02/2013
    04/03/2013
    04/04/2013
    04/05/201311VAL22
    04/05/2013

    I tried with UNION and UNION ALL, but getting the same result.

    Hello

    Try this:

    Select b.B_DATE, a, COLA1, one, COLA2

    from TABLEB b

    the left join TABLEA a

    On a.A_DATE = b.B_DATE

    and COLA1 = 11

    and COLA2 in ('VAL22')

    where B_DATE between to_date('2013-04-01','yyyy-mm-dd') AND to_date('2013-04-30','yyyy-mm-dd')

    ----

    Ramin Hashimzade

  • Using XQuery with PL/SQL, link the Variable

    I am only able to find an example of use of xquery with pl/sql.

    [http://www.comp.dit.ie/btierney/oracle11gdoc/appdev.111/b28369/xdb_xquery.htm#CBAEEJDE]

    Why is what they show only using bind variables? It's the only way it should be used, it provides a performance gain more simply by using the crossing clause and a passing beam a PL/SQL variable? I'm looking to implement a solution for my company using Xquery in PL/SQL. I am concerned that these procedures will be called during a flow of the user interface and performance it must be as soon as possible.

    A PL/SQL variable, column, or the output of another operation would be all be equivalent to a connection variable that PL/SQL compilation is concerned. Which would be bad practice would be to build in XQuery with the predicate hardcoded in the XQuery operation whenever the XQuery query has been run.

  • with the clause with union all?

    Hello

    I tried to use 'by' article with union all. .but it gives me error...
       with t1 as 
            (select '1'col1 from dual union all
             select '2' col2 from dual)select * from t1
             union 
            with t2 as 
            (select '3' col1 from dual union all
             select '4' col1 from dual )
              select * from t2
                
    What harm am I doing here? Thank you very much!!

    Use the WITH clause, once for you all the subqueries, and then add the main request;

    with t1 as
     (select '1' col1
      from dual
      union all
      select '2' col2
      from dual),
    t2 as
     (select '3' col1
      from dual
      union all
      select '4' col1
      from dual)
    select *
    from t1
    union
    select *
    from t2;
    
  • ODI 11 g multiple table with union join

    Hi all

    I have a problem with joining 4 different tables and union all of them.

    Here I want to generate this query;

    Select * from

    Table1, table2

    Join table2 = table1

    Union of all the

    Select * from

    Table 3, table 4

    Join table3 = table 4

    But I have not the same column that all the table, some are missing. When I write one - PL/SQL query I can easily add a false "NULL column1' column, but I can not how I do with ODI 11 g.

    I tried not to use "Active Mapping", but it does not work.

    I'm newbie ODI 11 g

    Thank you

    Myra

    Hi, Myra,.

    I'd even as in PL/SQL. In your table target add all the columns you need and overall data whatever you're missing some columns just put NULL in the mapping.

    Thank you

    Ajay

  • With the help of SCORE on top of view with UNION

    Hi guys,.

    I explain what I'm trying to do it quickly:

    2 tables: table1 and table2 with the same structure and have both a multi_column_datastore ctxsys.context.

    1 view: View1

    Select * from table1

    Union

    Select * from table2

    If I run:

    Select * from View1 WHERE contains (view1. Column1, '% textext %', 1) > 0;

    It works fine, I get the correct result.

    If I try to use the PARTITION function, I got an error:

    Select * from View1 WHERE contains (view1. Column1, '% textext %', 1) > 0 ORDER by SCORE (1);

    ORA-29921: auxiliary operator not supported with query to configure block

    I understand the problem is in the UNION inside the view, is it possible to keep work, filtering the VIEW?

    Thanks in advance

    There is no score in the view, so you cannot reference the score when you query the view.  In order to put the note in the view, you need a contains the clause, which requires a value.  A method to do this is to use sys_context.  Please see the reproduction of the problem and solution below.

    Scott@orcl12c >-reproduction of the problem:

    Scott@orcl12c > create the table1 table:

    2 (column1 varchar2 (30))

    3.

    Table created.

    Scott@orcl12c > insert into table1 values ('textext")

    2.

    1 line of creation.

    Scott@orcl12c > create table table2

    2 (column1 varchar2 (30))

    3.

    Table created.

    Scott@orcl12c > insert into table2 values ('textext")

    2.

    1 line of creation.

    Scott@orcl12c > start

    2 ctx_ddl.create_preference ('test_ds', 'multi_column_datastore');

    3 ctx_ddl.set_attribute ('test_ds', 'columns', "column1");

    4 end;

    5.

    PL/SQL procedure successfully completed.

    Scott@orcl12c > create index table1_idx on table1 (column1)

    2 indextype is ctxsys.context

    3 parameters ("test_ds of the data store")

    4.

    The index is created.

    Scott@orcl12c > create index table2_idx on the table2 (column1)

    2 indextype is ctxsys.context

    3 parameters ("test_ds of the data store")

    4.

    The index is created.

    Scott@orcl12c > create or replace view View1

    2 as

    3 select * from table1

    4 union

    5 select * from table2

    6.

    Created view.

    Scott@orcl12c > select * from View1 where contains (view1.column1, '% textext %', 1) > 0

    2.

    COLUMN1

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

    textext

    1 selected line.

    Scott@orcl12c > select * from View1 where contains > 0 (view1.column1,'%textext%',1) order by score (1)

    2.

    Select * from View1 where contains > 0 (view1.column1,'%textext%',1) order by score (1)

    *

    ERROR on line 1:

    ORA-29921: auxiliary operator not supported with query to configure block

    Scott@orcl12c >-solution:

    Scott@orcl12c > create or replace view View1

    2 as

    3. Select the partition (1) score, table1.* from table1

    4 where contains (table1. Column1, sys_context ('text_query', 'query_value'), 1) > 0

    5 union

    6 select score partition (1), table2.* from table2

    7 where contains (table2.column1, sys_context ('text_query', 'query_value'), 1) > 0

    8.

    Created view.

    Scott@orcl12c > create or replace context text_query using text_proc

    2.

    Context that is created.

    Scott@orcl12c > create or replace procedure text_proc

    2 (p_val in varchar2)

    3 as

    4 start

    5 dbms_session.set_context ('text_query', "query_value", p_val);

    6 end text_proc;

    7.

    Created procedure.

    Scott@orcl12c > text_proc exec ('% textext %')

    PL/SQL procedure successfully completed.

    Scott@orcl12c > set autotrace on explain

    Scott@orcl12c > select * from View1 by score

    2.

    MARK THE COLUMN1

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

    3 textext

    1 selected line.

    Execution plan

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

    Hash value of plan: 4090246122

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

    | ID | Operation | Name | Lines | Bytes | Cost (% CPU). Time |

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

    |   0 | SELECT STATEMENT |            |     2.    60.     8 (0) | 00:00:01 |

    |   1.  SORT ORDER BY |            |     2.    60.     8 (0) | 00:00:01 |

    |   2.   VIEW                          | VIEW1.     2.    60.     8 (0) | 00:00:01 |

    |   3.    UNIQUE FATE |            |     2.    58.     8 (50) | 00:00:01 |

    |   4.     UNION-ALL |            |       |       |            |          |

    |   5.      TABLE ACCESS BY INDEX ROWID | TABLE1.     1.    29.     4 (0) | 00:00:01 |

    |*  6 |       DOMAIN INDEX | TABLE1_IDX |       |       |     4 (0) | 00:00:01 |

    |   7.      TABLE ACCESS BY INDEX ROWID | TABLE2.     1.    29.     4 (0) | 00:00:01 |

    |*  8 |       DOMAIN INDEX | TABLE2_IDX |       |       |     4 (0) | 00:00:01 |

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

    Information of predicates (identified by the operation identity card):

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

    6 - access("CTXSYS".") CONTAINS "(" TABLE1".»)" Column1', SYS_CONTEXT ('text_query ',' query_v)

    Alou '), 1) > 0)

    8 - access("CTXSYS".") CONTAINS "(" TABLE2".»)" Column1', SYS_CONTEXT ('text_query ',' query_v)

    Alou '), 1) > 0)

    Note

    -----

    -the dynamic statistics used: dynamic sampling (level = 2)

    Scott@orcl12c >

  • Poblem with union/union all giving ORA-22950

    I use a select statement with the xmlelement to create an xml file.

    There the various unions end in 5, but I always bring a line through.

    I do like that as then I can use this as a cursor in my plsql without having to create lots of cursors when I only need to use a.
    That is to say.
    SELECT  xmlelement("QUOTATION",xmlagg(xmlelement(Quotation,
                          xmlelement(CUSTOMERNAME, customername),
                          xmlelement(QUOTE,quoteid )))xmlfile
    From cust, quote
    where custid=quotecustid
    and ptype = 'Q'
    UNION
    SELECT  xmlelement("SALES",xmlagg(xmlelement(SALES,
                          xmlelement(CUSTOMERNAME, customername),
                          xmlelement(QUOTE,salesid )))xmlfile
    From cust, sales
    where custid=salescustid
    and ptype = 'S'
    Then, I use a cursor to execute it in a ftp file folder I selected passing ptype as a parameter.

    If I use the union I get ORA-22950 - I have seen other people use UNION all around it.
    If I use union all I'll get a value for the SALE of any line that is

    Any ideas how I can get around this as do not want to continue to create cursors

    The use of different sliders is always the best approach IMO.
    All things considered, it should be more effective than that appearing more "smart" one.

    And there is no need to be explicit cursors, it could just be SELECT INTOs wrapped in a PL/SQL CASE statement, with the appropriate exception handler (if necessary).

    Anyway, if you want to stick with the single-cursor method, there are different ways to do this:

    (1) adding a column selector:

    SELECT xmlfile
    FROM (
      SELECT 'Q' as selector
           , xmlelement("QUOTATION",xmlagg(xmlelement(Quotation,
                      xmlelement(CUSTOMERNAME, customername),
                      xmlelement(QUOTE,quoteid )))xmlfile
      From cust, quote
      where custid=quotecustid
      and ptype = :1
      UNION ALL
      SELECT 'S'
           , xmlelement("SALES",xmlagg(xmlelement(SALES,
                      xmlelement(CUSTOMERNAME, customername),
                      xmlelement(QUOTE,salesid )))xmlfile
      From cust, sales
      where custid=salescustid
      and ptype = :1
    )
    WHERE selector = :1
    ;
    

    (2) adding a GROUP BY clause, so that XMLAgg returns nothing if no row is selected:

    SELECT xmlelement("QUOTATION",xmlagg(xmlelement(Quotation,
                    xmlelement(CUSTOMERNAME, customername),
                    xmlelement(QUOTE,quoteid )))xmlfile
    From cust, quote
    where custid=quotecustid
    and ptype = :1
    GROUP BY null
    UNION ALL
    SELECT xmlelement("SALES",xmlagg(xmlelement(SALES,
                    xmlelement(CUSTOMERNAME, customername),
                    xmlelement(QUOTE,salesid )))xmlfile
    From cust, sales
    where custid=salescustid
    and ptype = :1
    GROUP BY null
    ;
    

    (3) subqueries:

    SELECT case :1
            when 'Q' then ( SELECT ... )
            when 'S' then ( SELECT ... )
          end as xmlfile
    FROM dual
    ;
    
  • Problem with Union

    Hello

    I have a request below which I need the merger of two of them to get the result in a single query result, here's the query
    but the error me do is ORA-12704: incompatibility of character set, please let me know wat is the error in the query below

    Select rpad ('Roster_num', 20, "") 'Roster_num '.
    of the double

    UNION ALL

    SELECT
    SEPARATE
    RPAD (AP. EMPLOYEE_CODE, 20, "") 'Roster_num '.

    AR_EMPLOYEE_PERSONAL AP,
    AR_ADDRESS AA,
    AR_V_ROSTER_EMPLOYEE_DEF AD,
    AR_STATE_PROV_REGION ASP,
    AR_DEFINITION_TERRITORY ADT

    WHERE
    BDM PROJECT = 81 AND
    BPM EMPLOYEE_ID = AA. EMPLOYE_ID AND
    BPM EMPLOYEE_ID = AD. EMPLOYEE_ID (+) AND
    BAM STATE_PROV_REG_ID = ASP STATE_PROV_REG_ID AND
    BDM DEFINITION_TERRITORY_ID = ADT. DEFINITION_TERRITORY_ID (+)



    Thank you
    Sudhir

    Explanation with some examples:

    SQL>desc t_test;
    Name                           Null     Type
    ------------------------------ -------- -----------------
    COL1                                    NUMBER
    COL2                                    NUMBER
    COL3                                    NUMBER
    COL4                                    NCHAR(30)   
    

    We see that COL4 in the table is of type NCHAR.

    SQL>select * from t_test;
    COL1                   COL2                   COL3                   COL4
    ---------------------- ---------------------- ---------------------- ------------------------------
    1                      123                    3                      Roster
    2                      3                      4                      RKött
    3                      4                      2
    9                      10                     12
    11                     23                     43                                                    
    
    SQL>select rpad('Roster_num',20,' ') "Roster_num"
    from dual
    union all
    select RPAD(col4,20,' ')  "Roster_num" from t_test;
    
    Error starting at line 7 in command:
    select rpad('Roster_num',20,' ') "Roster_num"
    from dual
    union all
    select RPAD(col4,20,' ')  "Roster_num" from t_test
    Error at Command Line:7 Column:7
    Error report:
    SQL Error: ORA-12704: character set mismatch
    12704. 00000 -  "character set mismatch"
    *Cause:    One of the following
               - The string operands(other than an nlsparams argument) to an
               operator or built-in function do not have the same character
               set.
               - An nlsparams operand is not in the database character set.
               - String data with character set other than the database character
               set is passed to a built-in function not expecting it.
               - The second argument to CHR() or CSCONVERT() is not CHAR_CS or
               NCHAR_CS.
               - A string expression in the VALUES clause of an INSERT statement,
               or the SET clause of an UPDATE statement, does not have the
               same character set as the column into which the value would
               be inserted.
               - A value provided in a DEFAULT clause when creating a table does
               not have the same character set as declared for the column.
               - An argument to a PL/SQL function does not conform to the
               character set requirements of the corresponding parameter.
    *Action:
    

    Error returned for incompatibility of character as data types are not compatible.

    SQL>select rpad('Roster_num',20,' ') "Roster_num"
    from dual
    union all
    select TO_CHAR(RPAD(col4,20,' '))  "Roster_num" from t_test;
    
    Roster_num
    ------------------------------------------
    Roster_num
    Roster
    RKött                                                                                                                                                                                                    
    
    6 rows selected
    SQL>
    

    After the converted to the TO_CHAR problem solved

  • Join query with union

    Hi all

    I have two requests and I want to join this two query

    The column of the report should be like this
    item_number WK_30  WE_31
    1st request
    select 
    re.item_number, 
    nvl(le.quantity,0) - nvl(re.quantity,0) WK_30
    from BACKLOG_WEEK_WH_AFTR_ATP le, BACKLOG_ATP_GT_CW_IN re
    where le.item_number =re.item_number
    and to_number(substr(re.year_week,-2,2)) = to_number(to_char(sysdate,'IW'))+1
    2nd request
    select 
    re.item_number, 
    nvl(le.quantity,0) - nvl(re.quantity,0) WK_31
    from BACKLOG_WEEK_WH_AFTR_ATP le, BACKLOG_ATP_GT_CW_IN re
    where le.item_number =re.item_number
    and to_number(substr(re.year_week,-2,2)) = to_number(to_char(sysdate,'IW'))+2
    Thanks in advance

    Concerning

    Hello

    You are welcome.

    I think that the best way to understand that is to show what data is generated at each stage...

    1. we need to generate a list of lines that have every week, we are interested in swing on...

    (   SELECT
            to_number(to_char(sysdate,'IW')) + ROWNUM year_week_num
        FROM
            DUAL
        CONNECT BY LEVEL <= 5
    ) row_gen
    
    YEAR_WEEK_NUM
    -------------
               30
               31
               32
               33
               34
    

    2. must be added BACKLOG_WEEK_WH_AFTR_ATP lines in the calculations for the first week in the report

    SELECT
        le.item_number,
        le.quantity,
        to_number(to_char(sysdate,'IW'))+1 year_week_num
    FROM
        BACKLOG_WEEK_WH_AFTR_ATP le
    UNION ALL
    SELECT
        re.item_number,
        -re.quantity,
        to_number(substr(re.year_week,-2,2)) year_week_num
    FROM
        BACKLOG_ATP_GT_CW_IN re
    /
    ITEM_NUMBE   QUANTITY YEAR_WEEK_NUM
    ---------- ---------- -------------
    ITEM_1            200            30
    ITEM_2            600            30
    ITEM_1           -200            30
    ITEM_1           -100            33
    ITEM_2           -300            30
    ITEM_2           -200            32
    ITEM_3           -800            30
    ITEM_3           -400            34
    

    3. we must now repeat weekly, generated by the request of row_gen against all of the item_numbers returned by the above query and match them if possible to get the amount. Where there is no entry in BACKLOG_WEEK_WH_AFTR_ATP or BACKLOG_ATP_GT_CW_IN for a number of the week, we should use 0 as the quantity. The Partition Outer Join does for us.

    SQL>         select
      2              re.item_number,
      3              row_gen.year_week_num,
      4              NVL(re.quantity,0) qty
      5          from
      6              (   SELECT
      7                      to_number(to_char(sysdate,'IW')) + ROWNUM year_week_num
      8                  FROM
      9                      DUAL
     10                  CONNECT BY LEVEL <= 5
     11              ) row_gen LEFT OUTER JOIN
     12                      (   SELECT
     13                              le.item_number,
     14                              le.quantity,
     15                              to_number(to_char(sysdate,'IW'))+1 year_week_num
     16                          FROM
     17                              BACKLOG_WEEK_WH_AFTR_ATP le
     18                          UNION ALL
     19                          SELECT
     20                              re.item_number,
     21                              -re.quantity,
     22                              to_number(substr(re.year_week,-2,2)) year_week_num
     23                          FROM
     24                              BACKLOG_ATP_GT_CW_IN re
     25                       ) re
     26                  PARTITION BY (re.item_number)
     27                  ON ( row_gen.year_week_num = re.year_week_num)
     28  /
    
    ITEM_NUMBE YEAR_WEEK_NUM        QTY
    ---------- ------------- ----------
    ITEM_1                30        200
    ITEM_1                30       -200
    ITEM_1                31          0
    ITEM_1                32          0
    ITEM_1                33       -100
    ITEM_1                34          0
    ITEM_2                30       -300
    ITEM_2                30        600
    ITEM_2                31          0
    ITEM_2                32       -200
    ITEM_2                33          0
    ITEM_2                34          0
    ITEM_3                30       -800
    ITEM_3                31          0
    ITEM_3                32          0
    ITEM_3                33          0
    ITEM_3                34       -400
    
    17 rows selected.
    

    4. now, we have the base dataset that we need - she has all the amounts with the right directions so that we can simply add everything up as a sum of sumulative. That's what makes OVER(PARTITION BY re.item_number ORDER BY row_gen.year_week_num) SUM (NVL(re.quantity,0)) bit. He said baseically are all lines seen so far in the result set for each item number...

            select
                re.item_number,
                row_gen.year_week_num,
                NVL(re.quantity,0) qty,
                SUM(NVL(re.quantity,0)) OVER(PARTITION BY re.item_number ORDER BY row_gen.year_week_num) quantity
            from
                (   SELECT
                        to_number(to_char(sysdate,'IW')) + ROWNUM year_week_num
                    FROM
                        DUAL
                    CONNECT BY LEVEL <= 5
                ) row_gen LEFT OUTER JOIN
                        (   SELECT
                                le.item_number,
                                le.quantity,
                                to_number(to_char(sysdate,'IW'))+1 year_week_num
                            FROM
                                BACKLOG_WEEK_WH_AFTR_ATP le
                            UNION ALL
                            SELECT
                                re.item_number,
                                -re.quantity,
                                to_number(substr(re.year_week,-2,2)) year_week_num
                            FROM
                                BACKLOG_ATP_GT_CW_IN re
                         ) re
                    PARTITION BY (re.item_number)
                    ON ( row_gen.year_week_num = re.year_week_num)
    /
    ITEM_NUMBE YEAR_WEEK_NUM        QTY   QUANTITY
    ---------- ------------- ---------- ----------
    ITEM_1                30        200          0
    ITEM_1                30       -200          0
    ITEM_1                31          0          0
    ITEM_1                32          0          0
    ITEM_1                33       -100       -100
    ITEM_1                34          0       -100
    ITEM_2                30       -300        300
    ITEM_2                30        600        300
    ITEM_2                31          0        300
    ITEM_2                32       -200        100
    ITEM_2                33          0        100
    ITEM_2                34          0        100
    ITEM_3                30       -800       -800
    ITEM_3                31          0       -800
    ITEM_3                32          0       -800
    ITEM_3                33          0       -800
    ITEM_3                34       -400      -1200
    

    5. we can now rotate these data in columns - however, there is a small problem. For points 1 and 2 we have 2 lines for the week 30, running in the quantity column total is the same for both because the two lines appear at the same point in the game as defined by the order by clause. This means before rotate us, we must select one of the lines - or the other will do, they are both correct. If we do not have, the effect will be to double the cumulative sum (for point 1 is 0, so it does not appear) for this, we can use the ROW_NUMBER function...

            select
                re.item_number,
                row_gen.year_week_num,
                NVL(re.quantity,0) qty,
                SUM(NVL(re.quantity,0)) OVER(PARTITION BY re.item_number ORDER BY row_gen.year_week_num) quantity,
                ROW_NUMBER() OVER(PARTITION BY re.item_number, row_gen.year_week_num ORDER BY NULL) rn
            from
                (   SELECT
                        to_number(to_char(sysdate,'IW')) + ROWNUM year_week_num
                    FROM
                        DUAL
                    CONNECT BY LEVEL <= 5
                ) row_gen LEFT OUTER JOIN
                        (   SELECT
                                le.item_number,
                                le.quantity,
                                to_number(to_char(sysdate,'IW'))+1 year_week_num
                            FROM
                                BACKLOG_WEEK_WH_AFTR_ATP le
                            UNION ALL
                            SELECT
                                re.item_number,
                                -re.quantity,
                                to_number(substr(re.year_week,-2,2)) year_week_num
                            FROM
                                BACKLOG_ATP_GT_CW_IN re
                         ) re
                    PARTITION BY (re.item_number)
                    ON ( row_gen.year_week_num = re.year_week_num)
    /
    ITEM_NUMBE YEAR_WEEK_NUM        QTY   QUANTITY         RN
    ---------- ------------- ---------- ---------- ----------
    ITEM_1                30        200          0          1
    ITEM_1                30       -200          0          2
    ITEM_1                31          0          0          1
    ITEM_1                32          0          0          1
    ITEM_1                33       -100       -100          1
    ITEM_1                34          0       -100          1
    ITEM_2                30       -300        300          1
    ITEM_2                30        600        300          2
    ITEM_2                31          0        300          1
    ITEM_2                32       -200        100          1
    ITEM_2                33          0        100          1
    ITEM_2                34          0        100          1
    ITEM_3                30       -800       -800          1
    ITEM_3                31          0       -800          1
    ITEM_3                32          0       -800          1
    ITEM_3                33          0       -800          1
    ITEM_3                34       -400      -1200          1
    

    6. so now that we have a way to select one of the duplicate lines, we can move forward a pivot data by ensuring that us choose only 'first' line for each element for each week...

    SELECT
        item_number,
        SUM
        (   CASE
                WHEN year_week_num = to_number(to_char(sysdate,'IW'))+1 THEN
                    quantity
            END
        ) plus_1,
        SUM
        (   CASE
                WHEN year_week_num = to_number(to_char(sysdate,'IW'))+2 THEN
                    quantity
            END
        ) plus_2,
        SUM
        (   CASE
                WHEN year_week_num = to_number(to_char(sysdate,'IW'))+3 THEN
                    quantity
            END
        ) plus_3,
        SUM
        (   CASE
                WHEN year_week_num = to_number(to_char(sysdate,'IW'))+4 THEN
                    quantity
            END
        ) plus_4,
        SUM
        (   CASE
                WHEN year_week_num = to_number(to_char(sysdate,'IW'))+5 THEN
                    quantity
            END
        ) plus_5
    FROM
        (   select
                re.item_number,
                row_gen.year_week_num,
                SUM(NVL(re.quantity,0)) OVER(PARTITION BY re.item_number ORDER BY row_gen.year_week_num) quantity,
                ROW_NUMBER() OVER(PARTITION BY re.item_number, row_gen.year_week_num ORDER BY NULL) rn
            from
                (   SELECT
                        to_number(to_char(sysdate,'IW')) + ROWNUM year_week_num
                    FROM
                        DUAL
                    CONNECT BY LEVEL <= 5
                ) row_gen LEFT OUTER JOIN
                        (   SELECT
                                le.item_number,
                                le.quantity,
                                to_number(to_char(sysdate,'IW'))+1 year_week_num
                            FROM
                                BACKLOG_WEEK_WH_AFTR_ATP le
                            UNION ALL
                            SELECT
                                re.item_number,
                                -re.quantity,
                                to_number(substr(re.year_week,-2,2)) year_week_num
                            FROM
                                BACKLOG_ATP_GT_CW_IN re
                         ) re
                    PARTITION BY (re.item_number)
                    ON ( row_gen.year_week_num = re.year_week_num)
        )
    WHERE
        rn = 1
    GROUP BY
        item_number
    

    You need not add a join between BACKLOG_WEEK_WH_AFTR_ATP and BACKLOG_ATP_GT_CW_IN, because we are all summed up in the article number and all item numbers, we have selected two tables. The aggregation ensures that the quantities are added together against the item number.

    HTH

    David

  • List of values when using xquery with links?

    Hello

    What is the best way to build something like:
    collection('test.dbxml')/tree[type=('a','b','c')]
    with XQuery variable when it is unclear how many entries will be in the listeType beforehand? I would like to somehow put ('a', 'b', 'c') in a context of query as a variable to something like:
    collection('test.dbxml')/tree[type=$var]
    So, avoiding the risk of strengthening of string concatenation queries.

    Hello

    Java example:

    XmlResults res = manager.createResults();
    res.add(new XmlValue("a"));
    res.add(new XmlValue("b"));
    res.add(new XmlValue("c"));
    ....
    
    xmlQueryContext.setVariableValue("myVarName", res);
    

    Vyacheslav

  • Report with the query with union and parameters

    Hello

    We have an obligation to create a report with the request, which is the union and parameters.

    I intend to create a database for the report based on a query. But the problem here is that the way to pass parameters in the query.

    Request is something like that

    Select x.a, x.b, x.c
    x
    where x.year =: para1
    and x.status = 'A '.
    Union of all the
    Select x.a, x.b, x.c
    x
    where x.year =: para1 - 1
    and (x.status = 'c' and x.date =: para2 or x.status = 'I' and x.date < =: para2)

    Here x.year in the first select statement must be equal to: para1 and second select statement, it should be: para - 1.

    How this requirement can be achieved?

    Client don't want to separate worksheet, a parameter and another for the actual data that I tried with sys_context and it worked. But the client wants the result in a single sheet only... So I need to change their approach.

    Help, please.

    Thank you

    Hello
    Another option is to convert the request so that you will have the items from the selection
    for example on the query you provided that you can use:

    Select 'Curr' rec_type, x.a, x.b, x.c, x.year, x.date, x.status
    x
    where x.status = "A".
    Union of all the
    Select 'Prev' rec_type, x.a, x.b, x.c, x.year, x.date, x.status
    x
    where x.status in ('c', 'I')

    then, in the workbook, you will be able to create conditions such as:
    rec_type = 'Curr' and year =: para1

    rec_type = 'Prev' and year =: para1-1
    rec_type = 'Prev' and (status = 'c' and date =: para2 or status = 'I' and date)<=>

    Tamir

  • Problem with Union All

    Hello Experts,

    I'm still on the learning curve in PL/SQL and I have 2 different. I need to create a view that will merge these 2 tables.
    create view eft_view as
    select 
      BILL_TO_RETAILER      ,
      RETAILER_NAME         ,
      NAME_ON_BANK_ACCOUNT  ,
      BANK_ABA              ,
      BANK_ACCT             ,
      ON_LINE_AMOUNT        ,
      INSTANT_AMOUNT        ,
      TOTAL_AMOUNT          ,
      SOURCE                ,
      INSERTED_DATE         ,
      CDC                   from weekly_eft_temp union all
    select 
      BILL_TO_RETAILER  ,
      RETAILER_NAME     ,
      STATUS            ,
      ON_LINE_AMOUNT    ,
      INSTANT_AMOUNT    ,
      NON_SWEPT_AMT     ,
      TTYPE             ,
      EXCEPTION_REASON   from weekly_bill_expt_temp;
    I used the union of all, but it doesn't seem to work. I don't know where it's track. I searched on the net but his send me examples for 2 tables tat are similar.

    Any suggestions please

    You must replicate the columns that do not exist fill them with NULL values.

    Perhaps;

    create view eft_view as
      select bill_to_retailer,
             retailer_name,
             name_on_bank_account,
             bank_aba,
             bank_acct,
             null status,
             on_line_amount,
             instant_amount,
             total_amount,
             source,
             inserted_date,
             cdc,
             cast (null as number) non_swept_amt,
             null ttype,
             null exception_reason
        from weekly_eft_temp
      union all
      select bill_to_retailer,
             retailer_name,
             null name_on_bank_account,
             null bank_aba,
             null bank_acct,
             status,
             on_line_amount,
             instant_amount,
             null total_amount,
             null source,
             null inserted_date,
             nul cdc,
             non_swept_amt,
             ttype,
             exception_reason
        from weekly_bill_expt_temp;
    
  • Order by with Union

    select level as lvl --,1 as ordered 
    from dual
    connect by level <=5
    union all
    select rownum as lvl --,2 as ordered  
    from dual
    connect by level <=5 
    

    How to order the query after the UNION ALL clause in descending order

    My expected results

    1

    2

    3

    4

    5

    5

    4

    3

    2

    1

    Select * from (select level as lvl-, 1 as ordered

    of the double

    connect by level<>

    order by 1)

    Union of all the

    Select * from (select rownum as -lvl 2 as he ordered

    of the double

    connect by level<>

    order by 1 desc)

  • Transformation of XQuery with filter

    Hello

    I'm trying to implement a specific transformation: I need an object to a key filter.

    As input, I have this structure:

    <STRUCTURE>
      <item>   // multiplicy : *
        <MONTH>
        <INDICATOR />
        <LETA/>
      </item>
    </OBJECT_1>
    <OBJECT_2>
      <item>   // multiplicy : *
        <ORDER_NUMBER/>
        <ORDER_LINE_NUMBER/>
        <MONTH />
      </item>
    </OBJECT_2>
    </STRUCTURE>
    
    


    Here is an example:

    <STRUCTURE>
       <OBJECT_1>
          <item>
             <MONTH>2013_M06</MONTH>
             <INDICATOR>ABC</INDICATOR>
             <LETA>2012-04-24</LETA>
          </item>
          <item>
             <MONTH>2013_M05</MONTH>
             <INDICATOR>DEF</INDICATOR>
             <LETA>2012-04-24</LETA>
          </item>
       </OBJECT_1>
       <OBJECT_2>
          <item>
             <MONTH>2013_M06</MONTH>
             <ORDER_NUMBER>11111</ORDER_NUMBER>
             <ORDER_LINE_NUMBER>1</ORDER_LINE_NUMBER>
          </item>
          <item>
             <MONTH>2013_M06</MONTH>
             <ORDER_NUMBER>11111</ORDER_NUMBER>
             <ORDER_LINE_NUMBER>2</ORDER_LINE_NUMBER>
          </item>
          <item>
             <MONTH>2013_M05</MONTH>
             <ORDER_NUMBER>22222</ORDER_NUMBER>
             <ORDER_LINE_NUMBER>1</ORDER_LINE_NUMBER>
          </item>
       </OBJECT_2>
    </STRUCTURE>
    
    

    I need to have this result:

    <targetStructure>
       <object1>
             <month>2013_M06</month>
             <indicator>ABC</indicator>
             <leta>2012-04-24</leta>
              <object2>
                 <orderNumber>11111</orderNumber>
                 <orderLineNumber>1</orderLineNumber>
              </object2>
              <object2>
                 <orderNumber>11111</orderNumber>
                 <orderLineNumber>2</orderLineNumber>
              </object2>
          </object1>
          <object1>
             <month>2013_M05</month>
             <indicator>DEF</indicator>
             <leta>2012-04-24</leta>
             <object2>
                 <orderNumber>22222</orderNumber>
                 <orderLineNumber>1</orderLineNumber>
              </object2>
          </object1>
       </object1>
    </targetStructure>
    
    

    My transformation XQ is like this:

    (:: pragma bea:global-element-parameter parameter="$STRUCTURE" element="ns1:STRUCTURE" location="xxx" ::)
    (:: pragma bea:global-element-return element="ns0:targetStructure" location="xxy" ::)
    
    declare namespace ns1 = "urn:aa";
    declare namespace ns0 = "http://vvv.com";
    declare namespace xf = "http://tempuri.org/cc/";
    
    
    declare function xf:myTransformation($z_STRUCTURE1 as element(ns1:STRUCTURE))
        as element(ns0:targetStructure)
    <targetStructure>
              {
                        for $item in $z_STRUCTURE1/ns1:OBJECT_1/ns1:item
                        return
                            <object1>
                                {
                                    for $MONTH in $item/ns1:MONTH
                                    return
                                        <month>{ data($MONTH) }</month>
                                }
                                {
                                    for $INDICATOR in $item/ns1:INDICATOR
                                    return
                                        <indicator>{ data($INDICATOR) }</indicator>
                                }
                                {
                                    for $LETA in $item/ns1:LETA
                                    return
                                        <month>{ data($LETA) }</month>
                                }
                               {
                                    for $item0 in $STRUCTURE/ns1:OBJECT_1/ns1:item
                                    return
                                        <object2>
                                         {
                                               for $ORDER_NUMBER in $item/ns1:ORDER_NUMBER
                                               return
                                                     <orderNumber>{ data($ORDER_NUMBER) }</orderNumber>
                                         }
                                         {
                                              for $ORDER_LINE_NUMBER in $item/ns1:ORDER_LINE_NUMBER
                                              return
                                                   <orderLineNumber>{ data($ORDER_LINE_NUMBER) }</orderLineNumber>
                                        }
                                       </object2>
                               }
              }
    </targetStructure>
    
    

    As you can see, I had everyone in each object1 object2, while I only need the object2 when the MONTH is equal to the object1 one...

    I tried to replace line 32, by

    for $item0 in $STRUCTURE/ns1:OBJECT_1/ns1:item[ns1:month=$item/ns1:MONTH/text()]
    
    

    ... or some variations, but I've never had what I expected...

    Any ideas?

    Concerning

    Use of xquery below: -.

    XQuery version "1.0" encoding "Cp1252";

    (: parameter pragma = "$anyType1" type = "xs: anyType" ::))

    (: pragma type = "xs: anyType" ::))

    declare namespace xf = "http://tempuri.org/OSB%20Project%201/XQ/Test2/";

    declare function xf:Test2 ($anyType1 as element (*))

    {element (*)}

    Let the $input: =.

    2013_M06

    ABC

    2012-04-24

    2013_M05

    DEF

    2012-04-24

    2013_M06

    11111

    1

    2013_M06

    11111

    2

    2013_M05

    22222

    1

    Let $month: = fn:distinct-values($input/OBJECT_1//MONTH/text())

    Let $out: = {}

    for $x in 1-fn:count ($month)

    return

    {$month [$x]}

    {$input/OBJECT_1/item[./MONTH=$month[$x]]/INDICATOR/text ()}

    {$input/OBJECT_1/item[./MONTH=$month[$x]]/LETA/text ()}

    {for $y in the $input / OBJECT_2 / item}

    where $y/MONTH/text () = $month [$x]

    return

    {$y} / ORDER_NUMBER/text)

    {$y} / ORDER_LINE_NUMBER/text)

    }

    }

    return $out

    };

    declare the variable $anyType1 as element (*) external;

    XF:Test2 ($anyType1)

  • show all columns with union all

    Hi all
    select m_id, total, cat_id
    from scott.maintenance
    where prod_id = 1
    union all
    select m_id, total, prod_id
    from scott.maintenance
    where prod_id = 4
    How can I view all (and not common) columns of the two tables when I use union all like
    m_Id, total, cat_id, prod_id

    Thank you
    Johnny

    Hi, Johnny,.

    user9542267 wrote:
    Hi all

    select m_id, total, cat_id
    from scott.maintenance
    where prod_id = 1
    union all
    select m_id, total, prod_id
    from scott.maintenance
    where prod_id = 4
    

    How can I view all (and not common) columns of the two tables when I use union all like
    m_Id, total, cat_id, prod_id

    Thank you
    Johnny

    There is no need to make a trade UNION for this:

    SELECT  *
    FROM    scott.maintenance
    WHERE   prod_id IN (1, 4)
    ;
    

    If you really need to do a UNION and basic tables were the same or had the same number and types of columns, then you can use SELECT * in the two branches of the UNION:

    SELECT  *
    FROM    scott.maintenance
        --
    UNION ALL
        --
    SELECT  *
    FROM    foo.maintenance
    ;
    

    If the columns have different names in the two tables, the names of the first branch of the UNION will be used in the output.

    In all cases, you can add literal NULL values to the SELECT one or more branches of the UNION clause:

    SELECT  ename     AS name
    ,       hiredate
    ,       deptno
    FROM    scott.emp
        --
    UNION ALL
        --
    SELECT  dname     AS name        -- alias not necessary, but helpful
    ,       NULL      AS hiredate    -- alias not necessary, but helpful
    ,       deptno
    FROM    scott.dept
    ;
    

    Depending on your tables and your requirements of yor, you might be able to use SELECT * in a branch of the UNION.

    Published by: Frank Kulash, February 15, 2011 12:29

Maybe you are looking for

  • H9-1135 phoenix upgrade graphics card inquiry, please help!

    I am hoping to update my video graphics card. Can my Phoenix H9-1135 (stock to date system) support this video graphics card? GIGABYTE GV - N760OC - 4GD GeForce GTX 760 4GB 256 - bit GDDR5 PCI Express 3.0 HDCP Ready gets 3 X 450W video card Posted be

  • Purchase receipt email

    I got this email today from app9@***: Dear *.Thank you for buying the product following on 11/03/2016 10:37:39 Product name: Clash of the DragonsOrder number: GB870065BDDate received: 26/02/2016 11:10:39Order total: €35.99If you do not allow this pur

  • Wishlist App for a7RII

    I don't know if there is no Forum App and because Sony does not allow 3rd party apps 3:rd I guess one must wish apps. 1. an application with the outbreak of the movement. The 'sensor' knows queries why not have an option to trigger?

  • reset the factory default DV6 hp pavilion

    I have a laptop HP Pavilion DV6 aged of 5 years I want to restore factory settings in order to give to my nephew. I either lost or never done a system recovery disks. The computer did not come with recovery discs. The computer came pre-installed with

  • Availability of LabVIEW 64-bit for Mac?

    Hello world A quick search of the forum seems to indicate that there may have been some 64-bit versions of LV for Mac produced, but I can't seem to find all recent messages, or how I could get a copy.  Does anyone know if there are available versions