Hierarchical query with out using Connect by prior

Hi Guys,
I am supporting a product which is enterprise based and only allowd to write queries which are ANSII standard.
I have an requirement like If I provide the child I need to know all the parents till  highest level.
My table structure is like below
Table_name :  Org_unit
Columns are
Org_unit_id name desc  parent_org_unit_id
I wil pass the org_unit id and want to list all the parents of the chile org_unit_id and it has to be accomplished without  using connec by prior.
Please suggest me some ideas and aprroches
I am using Orcle 11g version

Hi,
960593 wrote:
Hi Guys,
I am supporting a product which is enterprise based and only allowd to write queries which are ANSII standard.
I have an requirement like If I provide the child I need to know all the parents till  highest level.
My table structure is like below
Table_name :  Org_unit
Columns are
Org_unit_id name desc  parent_org_unit_id
I wil pass the org_unit id and want to list all the parents of the chile org_unit_id and it has to be accomplished without  using connec by prior.
Please suggest me some ideas and aprroches
I am using Orcle 11g version
The data model you posted (org_unit_id as primary key, parent_org_unit_id as foreign key to the same table for the parent, when there is a parent) is called the Adjacency Model because it keeps track of which nodes are adjacent (or next to) each other.
I'm familiar with 2 other ways to model hierarchies: the Nested Sets Model, and what I call the Lineage Model.  I'll show how to find a given node's ancestors (in hierarchical order) in each model.  Neither the Nested Sets nor the Lineage Model requires CONNECT BY or recursive WITH clauses to work.
The following table contains all the columns necessary for using each of these 3 models:
     EMPNO        MGR ENAME      LINEAGE                    NS_LOW NS_HIGH
      7839            KING       /7839/                          1      28
      7698       7839 BLAKE      /7839/7698/                     2      13
      7499       7698 ALLEN      /7839/7698/7499/                3       4
      7900       7698 JAMES      /7839/7698/7900/                5       6
      7654       7698 MARTIN     /7839/7698/7654/                7       8
      7844       7698 TURNER     /7839/7698/7844/                9      10
      7521       7698 WARD       /7839/7698/7521/               11      12
      7782       7839 CLARK      /7839/7782/                    14      17
      7934       7782 MILLER     /7839/7782/7934/               15      16
      7566       7839 JONES      /7839/7566/                    18      27
      7902       7566 FORD       /7839/7566/7902/               19      22
      7369       7902 SMITH      /7839/7566/7902/7369/          20      21
      7788       7566 SCOTT      /7839/7566/7788/               23      26
      7876       7788 ADAMS      /7839/7566/7788/7876/          24      25
The Lineage Model keeps track of all of a given nodes ancestors, so if all you need to find are the primary keys of a given node, it's really trivial: it's all in the lineage column.  If you want to find more information about those ancestors, then you can do a self-join, like this:
SELECT    a.empno, a.ename, a.lineage
FROM      emp  a
JOIN      emp  d   ON  d.lineage  LIKE '%/' || a.empno || '/%'
WHERE     d.ename  IN ('ADAMS')
ORDER BY  d.ename
,         a.lineage
Output:
     EMPNO ENAME      LINEAGE
      7839 KING       /7839/
      7566 JONES      /7839/7566/
      7788 SCOTT      /7839/7566/7788/
      7876 ADAMS      /7839/7566/7788/7876/
The Nested Sets model is harder to understand.
Imagine everyone in the hierarchy standing on a wide staircase, as if for a group picture; everyone on the same level standing on the same step.  Everyone is holding up an umbrella that is wide enough to cover himself and all the people who are under him in the hierarchy.  The people with no underlings have small umbrellas, denoted like this "<-SMITH->", and peole that manage others have bigger umbrellas, like this: <-------- JONES -------->.  So the group picture might look like this:
<-------------------------------------------- KING --------------------------------------------->
  <---------------------- BLAKE --------------------->  <-- CLARK -->  <-------- JONES -------->
   <-ALLEN-> <-JAMES-> <-MARTIN-> <-TURNER-> <-WARD->    <-MILLER->     <-- FORD--> <--SCOTT-->
                                                                         <-SMITH->   <-ADAMS->
Each parent's umbrella covers all of his descendants (children, grandchildren, etc.), and nobody else.
Now draw vertical lines trom the edges of each umbrella downwards, and number those lines from left to right:
<-------------------------------------------- KING ------------------------------------------------>
|                                                                                                  |
| <---------------------- BLAKE --------------------->  <-- CLARK ->   <-------- JONES ----------> |
| |                                                  |  |          |   |                         | |
| |<-ALLEN-> <-JAMES-> <-MARTIN-> <-TURNER-> <-WARD->|  |<-MILLER->|   |<-- FORD--> <--SCOTT---> | |
| ||       | |       | |        | |        | |      ||  ||        ||   ||         | |          | | |
| ||       | |       | |        | |        | |      ||  ||        ||   ||<-SMITH->| |<-ADAMS-> | | |
| ||       | |       | |        | |        | |      ||  ||        ||   |||       || ||       | | | |
                                           1 1      11  11        11   112       22 22       2 2 2 2
1 23       4 5       6 7        8 9        0 1      23  45        67   890       12 34       5 6 7 8
The numbers corresponding to the left arnd right edges of each umbrella are what I called ns_low and ns_high in the table.  Each employyes ns_low and ns_high numbers will be inside the range of each of his ancestors ns_low and ns_high.
To find the ancestors of a given node in the nested set model you can do this:
SELECT   a.empno, a.ename, a.ns_low, a.ns_high
FROM   emp  a
JOIN      emp  d  ON  d.ns_low  BETWEEN  a.ns_low
                                AND      a.ns_high
WHERE     d.ename  IN ('ADAMS')
ORDER BY  d.ename
,         a.ns_low
Both the Lineage and Nested Sets models are good for tree structures only, whereas the Adjacency Model can handle other kinds of graphs, including graphs with loops.
Both the Lineage and Nested Sets models can be very difficult to maintain if the hierarchy is re-organized.
I'd like to repeat some of the warnings that others have made.  You could write separate code for each system (Oracle, SQL Server, ...) that you want to run in, and the code for each system will be more or less different.  You're looking for some code that will get the same results in all systems.  That code will be more complicated that the most complicated of the single-system versions, and it will be sloweer than the slwoest of the single-system versions.  You're giving up a lot of functionality, and probably also ease of maintenance, by writing code that has to work on multiple systems without changes.
Here's how I created the emp table shown above from scott.emp:
CREATE TABLE    emp
AS
WITH    connect_by_results  AS
    SELECT  empno, mgr, ename
    ,       LEVEL   AS lvl
    ,       ROWNUM  AS r_num
    ,       SYS_CONNECT_BY_PATH (empno, '/') || '/'   AS lineage
    FROM scott.emp
    START WITH mgr IS NULL
    CONNECT BY mgr = PRIOR empno
    ORDER SIBLINGS BY ename
SELECT empno, mgr, ename, lineage
,       (2 * r_num) - lvl            AS ns_low
,       (2 * r_num) + ( 2 * (
                                SELECT  COUNT (*)
                                FROM    connect_by_results
                                WHERE   lineage  LIKE '%/' || cbr.empno || '/%'
                    - (lvl + 1)      AS ns_high
FROM connect_by_results   cbr
This relies on the fact that the hierarchy in scott.emp has only one root (that is, a node with no parent).  Computing the Nested Sets numbers is a little more complicated if you can have multiple roots.

Similar Messages

  • Please suggest a select query / sub query with out using any subprograms or

    source table: Three columns ORIGIN, DESTINATION,MILES
    Origin      Destination Miles
    Sydney      Melbourne      1000
    Perth      Adelaide      3000
    Canberra      Melbounre      700
    Melbourne      Sydney           1000
    Brisbane      Sydney           1000
    Perth      Darwin           4000
    Sydney      Brisbane      1000
    out put :Three columns ORIGIN, DESTINATION,MILES
    Duplicate routes are to be ignored so the output is
    Origin      Destination      Miles
    Sydney      Melbourne      1000
    Perth      Adelaide      3000
    Canberra      Melbounre      700
    Brisbane      Sydney           1000
    Perth      Darwin           4000
    Please suggest a select query / sub query with out using any subprograms or functions/pkgs to get the out put table.

    Hi,
    user9368047 wrote:
    ... Please suggest a select query / sub query with out using any subprograms or functions/pkgs to get the out put table.Why? If the most efficient way to get the results you want involves using a function, why wouldn't you use it?
    Here's one way, without any functions:
    SELECT     a.*
    FROM           source_table  a
    LEFT OUTER JOIN      source_table  b  ON   a.origin          = b.destination
                                          AND  a.destination       = b.origin
                          AND  a.miles          = b.miles
    WHERE   b.origin  > a.origin    -- Not b.origin > b.origin
    OR     b.origin  IS NULL
    ;If you'd care to post CREATE TABLE and INSERT statements for your sample data, then I could test this.
    Edited by: Frank Kulash on Nov 6, 2012 7:39 PM
    Corrected WHERE clause after MLVrown (below)

  • Re execute query with out using a time

    Hi
    I want to refresh data in many based tables blocks automaticly with out using a timer, lest say ever 2 m refresh the data, is there is any soluation for that
    best regards

    Hi!
    If you use a timer, the mouse cursor will not move...
    But may the content of an active item get selected, if the timer elapse.
    This is just happen, if you have a form open with a running timer
    and call another form with the open_form build-in.
    When the timer in the calling form elapse, a context switch to
    the calling form occurs and when the focus come back to the called form,
    may the current-item value is getting selected. But the mouse cursor is not moving!
    May you try to requery your block with a timer and see what's happen.
    Regards

  • Hierarchical Query with Rollup Sum (CONNECT BY with GROUP BY ROLLUP)

    Hi all,
    Imagine the following scenario: i have an ACCOUNT table which holds accounts and their hierarchy (currently 5 levels), and a BALANCE table which holds balance records for the accounts. Only CHILD accounts (level 5) have records in the BALANCE table. Simple example:
    CREATE TABLE accounts (account_code VARCHAR2(30), parent_account VARCHAR2(30), account_desc VARCHAR2(400));
    CREATE TABLE balances (account_code VARCHAR2(30), balance_amount NUMBER(18,2));
    INSERT INTO ACCOUNTS VALUES ('TOT',NULL,'Total');
    INSERT INTO ACCOUNTS VALUES ('ANA1','TOT','General Expenses');
    INSERT INTO ACCOUNTS VALUES ('4801001','ANA1','Small Expenses');
    INSERT INTO ACCOUNTS VALUES ('4801002','ANA1','Transportation');
    INSERT INTO ACCOUNTS VALUES ('ANA2','TOT','Health Expenses');
    INSERT INTO ACCOUNTS VALUES ('4802001','ANA2','Healthcare');
    INSERT INTO ACCOUNTS VALUES ('4802002','ANA2','Facilities');
    INSERT INTO BALANCES VALUES ('4801001', 2000);
    INSERT INTO BALANCES VALUES ('4801002', 1000);
    INSERT INTO BALANCES VALUES ('4802001', 3000);
    INSERT INTO BALANCES VALUES ('4802002', 4000);What i need in this scenario is to run a hierarchical query, where for each node i compute the sum of all its children (In LEAF nodes which are the child accounts, this sum is the value in BALANCES itself). Final Result would be:
    TOT -> 10000
      ANA1 -> 3000
        4801001 -> 2000
        4801001 -> 1000
      ANA2 -> 7000
        4802001 -> 3000
        4802002 -> 4000I have tried various ways, and found out a workaround which works for a fixed amount of levels, basically it builds the hierarchy and computes the SYS_CONNECT_BY_PATH, then splits this as a regular expression and uses GROUP BY ROLLUP to compute the higher levels. Then i assemble it again, now with the computed values. Below is the example query:
    select level
        , NVL (vfinal.child_account,'TOTAL') ||' - '||
                            ( SELECT account_desc
                                FROM accounts
                               WHERE account_code = vfinal.child_acct ) account_name
         , to_char(sum_bal, 'fm999g999g999g990') as rolled_up_balance
      from
    select coalesce( princ.lvl3, princ.lvl2, princ.lvl1 ) child_acct
         , DECODE ( princ.lvl2 , NULL
                                     , NULL
                                     , DECODE ( princ.conta_lvl3, NULL
                                     , princ.conta_lvl1,princ.conta_lvl2 ) ) parent_acct
         , sum(princ.balance_amount) sum_bal
    from (
    select hier.lvl1
         , hier.lvl2
         , hier.lvl3
         , hier.parent_account
         , hier.account_code child_acc
         , bal.balance_amount
      from ( select level 
                  , sys_connect_by_path( account_code, '/' ) hierarchy_acct
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,3) lvl3
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,2) lvl2
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,1) lvl1
                  , account_code
                  , parent_account 
               from accounts acc
               where level <= 3
               start with parent_account is null
               connect by nocycle prior account = parent_account
               order siblings by parent_account
               ) hier
          , balances  bal
      where bal.cod_conta  = hier.account_code
    ) princ
    where princ.lvl1 is not null
    group by rollup ( princ.lvl1
                    , princ.lvl2
                    , princ.lvl3 )
    order by princ.conta_lvl1
           , princ.conta_lvl2
           , princ.conta_lvl3
    ) vfinal
    where child_acct is not null
    start with parent_acct is null
    connect by nocycle prior child_acct = parent_acctAll said and done, what i need is to do the same thing for infinite levels, because this query has 3 fixed levels. Do you know how can i structure a new query where, independently of the number of levels, the parent sums are all rolled up like this?
    Thanks a lot in advance! Best Regards!
    Thiago
    Edited by: Thiago on Sep 6, 2011 11:31 AM
    Edited by: Thiago on Sep 6, 2011 1:01 PM

    Hi,
    Thiago wrote:
    Hi all,
    Imagine the following scenario: i have an ACCOUNT table which holds accounts and their hierarchy (currently 5 levels), and a BALANCE table which holds balance records for the accounts. Only CHILD accounts (level 5) have records in the BALANCE table. Simple example:
    CREATE TABLE accounts (account_code VARCHAR2(30), parent_account VARCHAR2(30), account_desc VARCHAR2(400));
    CREATE TABLE balances (account_code VARCHAR2(30), balance_amount NUMBER(18,2));
    INSERT INTO ACCOUNTS ('TOT',NULL,'Total');
    INSERT INTO ACCOUNTS ('ANA1','TOT','General Expenses');
    INSERT INTO ACCOUNTS ('4801001','ANA1','Small Expenses');
    INSERT INTO ACCOUNTS ('4801002','ANA1','Transportation');
    INSERT INTO ACCOUNTS ('ANA2','TOT','Health Expenses');
    INSERT INTO ACCOUNTS ('4802001','ANA2','Healthcare');
    INSERT INTO ACCOUNTS ('4802002','ANA2','Facilities');
    INSERT INTO BALANCES ('4801001', 2000);
    INSERT INTO BALANCES ('4801001', 1000);
    INSERT INTO BALANCES ('4802001', 3000);
    INSERT INTO BALANCES ('4802001', 4000);
    Thanks for posting the CREATE TABLE and INSERT statements. Remember why you do it: so that the people who want to help you can re-create the problem and test their ideas. If the statments don't work, then they are not so useful. None of the INSERT statements you posted work: they all need a VALUES keyword. Please test those statments before you post them.
    Also, make sure that the reuslts you post correspond to the sample data you post. In your sample data, there are no rows in balances for account_codes '4801002' or '4802002'.
    I think you want something like this:
    WITH  connect_by_results      AS
         SELECT     CONNECT_BY_ROOT account_code     AS root_account_code
         ,     account_code
         FROM     accounts
                             -- NOTE: No START WITH clause
         CONNECT BY     parent_account     = PRIOR account_code
    SELECT       c.root_account_code     || ' -> '
                          || TO_CHAR (SUM (b.balance_amount))     AS txt
    FROM           connect_by_results  c
    LEFT OUTER JOIN      balances          b  ON  c.account_code = b.account_code
    GROUP BY  c.root_account_code
    ;

  • Oracle query with out using self join

    hi friends,
    i have one table for exeample PERSTATUS
    pk/fK STUDENT NUMBER SUBJECT MARKS STATUS
    1 ACCOUNTS 15 RED
    1 MATHS 35 YELLOW
    1 SCINECE 45 GREEN
    2 ACCOUNTS 55 BROWN
    2 MATHS 35 YELLOW
    2 SCINECE 45 GREEN
    3 ACCOUNTS 15 RED
    3 MATHS 35 YELLOW
    3 SCINECE 45 GREEN
    i want students how status is both red and yellow so i am using self join
    i want students status is both red and yellow so i am using self join
    SELECT PS.STUDENTNUMBER,PS.STATUS,PS.STATUS1 FROM PERSTATUS PS ,PERSTATUS PS1
    WHERE PS.STUDENTNUMBER-PS1.STUDENTNUMER
    PS.STATUS='RED' AND PS1.STAUTS='YELLOW'
    i want students status is both RD and YELLOW AND GREEN so i am using self join( two self joinS}
    SELECT PS.STUDENTNUMBER,PS.STATUS,PS.STATUS,PS2.STATUS FROM PERSTATUS PS ,PERSTATUS PS1,PERSTATUS PS2
    WHERE PS.STUDENTNUMBER-PS1.STUDENTNUMER AND PS.STUDENTNUMBER-PS2.STUDENTNUMBER
    PS.STATUS='RED' AND PS1.STAUTS='YELLOW' AND PS2.STAUTUS='GREEN'
    if i require MORE STATUS then more self joins required, is there any alternative to achive this
    and if results comes in multiple rows are accepted (since with the above query result will come in single row)
    i tried to use group by (studentnumber,status) with status='red' and status='yellow'
    but it is not possible could you povidet he solution

    Hi,
    Whenever you have a problem, please post CREATE TABLE and INSERT statements for your sample data, and the exact results you want from that data. Explain how you get those results from that data.
    See the forum FAQ {message:id=9360002}
    Here's an example of how to post the sample data:
    CREATE TABLE     perstatus
    (       studentnumber     NUMBER
    ,     subject          VARCHAR2 (10)
    ,     marks          NUMBER
    ,     status          VARCHAR2 (10)
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (1,           'ACCOUNTS', 15,       'RED');
    INSERT INTO perstatus (studentnumber, subject  ,  marks, status)
           VALUES           (1,           'MATHS',        35,       'YELLOW');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (1,           'SCINECE',  45,       'GREEN');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (2,           'ACCOUNTS', 55,       'BROWN');
    INSERT INTO perstatus (studentnumber, subject  ,  marks, status)
           VALUES           (2,           'MATHS',        35,       'YELLOW');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (2,           'SCINECE',  45,       'GREEN');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (3,           'ACCOUNTS', 15,       'RED');
    INSERT INTO perstatus (studentnumber, subject  ,  marks, status)
           VALUES           (3,           'MATHS',        35,       'YELLOW');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (3,           'SCINECE',  45,       'GREEN');You were on the right track, thinking about GROUP BY. You're interested in something about the whole group of rows that has the same studentnumber. Looking at any individual row won't tell you if that row is part of the group you're interested in or not.
    If you want to see information about the group as a whole, you can do the whole job with GROUP BY. In this case, studnetnumber is the only thing that an entire group has in common. If you wanted to see the studentnumbers that had both RED and YELLOW, that is:
    STUDENTNUMBER
                1
                3here's one way you could do it:
    SELECT       studentnumber
    FROM       perstatus
    WHERE       status     IN ('RED', 'YELLOW')
    GROUP BY  studentnumber
    HAVING       COUNT (DISTINCT status) = 2  -- That is, both RED and YELLOW
    ORDER BY  studentnumber
    ;But say you wanted to see details about individuals in the group; for example, say we want to see all the columns for students that have all 3 of RED, YELLOW and GREEN, like this:
    STUDENTNUMBER SUBJECT         MARKS STATUS
                1 SCINECE            45 GREEN
                1 ACCOUNTS           15 RED
                1 MATHS              35 YELLOW
                3 SCINECE            45 GREEN
                3 ACCOUNTS           15 RED
                3 MATHS              35 YELLOWWe used the aggregate COUNT function earlier, but aggregate functions require collapsing the results down to one row per group.
    However, most of the aggregate functions, like COUNT, have analytic counterparts, that can give the same results without collapsing the result set. Here's one way to get the results above, using the analytic COUNT function:
    WITH     got_cnt          AS
         SELECT  studentnumber, subject, marks, status
         ,     COUNT ( DISTINCT CASE
                                   WHEN  status  IN ('RED', 'YELLOW', 'GREEN')
                             THEN  status
                               END
                    ) OVER (PARTITION BY  studentnumber)     AS cnt
         FROM    perstatus
    SELECT    studentnumber, subject, marks, status
    FROM       got_cnt
    WHERE       cnt  = 3
    ORDER BY  studentnumber
    ,            status
    ;

  • How to Execute  sql query in PL/SQL ( a variable) with out using Cursor or REF cursor

    Hi
    I am building a dynamic query based on some conditions
    as an example
    v_query varchar2(2000);
    x1 varchar2(20);
    y1 varchar2(20);
    z1 varchar2(20);
    v_query := ' Select x,y,z into x1,y1,z1 From ... ';
    Is there any way to execute the query with out using cursor or ref cursor..
    Thanks
    Arun

    Both Tod and Eric provided valid responses given the format of the queory you supplied. Howver, if you want to use dynamic sql in either way, you need to be absolutely certain that your query will always only return a single row (e.g. SELECT COUNT(*) FROM mytable), because if it retuns more than one, your procedure will break unless you have an exception handler to handle either TOO_MANY_ROWS or OTHERS.
    If you want to pull in a lot of data without walking a cursor, you should look at the BULK COLLECT options.

  • Can i connect a external hard drive to apple tv 3 generation, for see my movies itunes with out use streaming or icloud?

    can i connect a external hard drive to apple tv 3 generation, for see my movies itunes with out use streaming or icloud?  in apple tv 3 and 2?
    That  i want to know is i can connect a external hard drive to apple tv, for see my movies that i keep in my external hard drive,  i dont want to see then  whit the streaming and icloud, or used my  laptop o pc for access de movies and stuff.
    i put iny spanish to, because i feel my english is not so good, but i hope you understand me.
    if i can´t  connect a external hard  drive, wich others media players divices you know that can see itunes movies?
    ¿quisiera saber si se puede conectar una memoria externa al apple tv, para ver el contenido de itunes que tengo guardado en esa memoria como peliculas, ect?
    lo que no quiero es usar  la icloud, o el servicio streamig para ver mi contenido, ni tener que usar la computadora para ver mi contenido el la tv?
    y de no poderse conectar  que otros dispositivos media pleyer conoces para ver peliculas de itunes  en la tv?

    Welcome to the Apple Community.
    can i connect a external hard drive to apple tv 3 generation
    Unfortunately not.

  • Can I use ipod touch 5th to mirror my screen on Apple TV via Airplay with out wifi connection?

    Can I use ipod touch 5th to mirror my screen on Apple TV via Airplay with out wifi connection?

    Welcome to the Apple Community.
    Peer-to-peer AirPlay
    With peer-to-peer AirPlay, your iOS device and Apple TV don't need to be on the same Wi-Fi network. If you have one of these products, you can use peer-to-peer AirPlay:
    * iPhone 5 or later, iPad (3rd generation or later), iPad mini, or iPod touch (5th generation) using iOS 8 or later.
    * Apple TV (3rd generation rev A, model A1469 or later) with Apple TV software 7.0 or later. Find out which Apple TV model you have.
    To use peer-to-peer AirPlay, your iOS device needs to have both Wi-Fi and Bluetooth turned on.

  • Is there any way to connect an ipad to a ethernet  cord or connection with out using wi fi

    Is there any way to connect an ipad to a ethernet  cord or connect with out using wi fi?  Thank  you

    The closest you can come, without having a 3G iPad is to have a cellular mobile hotspot like the Mifi or such device, use that to get to wifi, or to tether it to a cell phone.

  • With out using pivot function need a Query

    Hi
    I am having table which has 7 columns
    data in table:
    ID,Region,area, year-month,  sales_target, actual_sales,
    1, abc,    xyz,   200907,       1000,          500
    2, abc,    pqr,   200908,       2000,         1500
    3, mnr,   xyz,   200907,       3000,          2000
    I need the data in year and  month with out using pivot funtion
    intial
    region, area,    jul,   aug, sep, oct .......jun
    abc,     xyz,    1000,0,     0,    0...         0
    actual
    region, area,    jul,   aug, sep, oct .......jun
    abc,     xyz,    500,   0,     0,    0...         0Thanks

    Here it is
    with d as ( select 1 ID, 'abc' Region, 'xyz' area, 200907 yearmonth,  1000 sales_target, 500 actual_sales from dual
    union all   select 2, 'abc',    'pqr',   200908,       2000,         1500 from dual
    union all   select 3, 'mnr',   'xyz',   200907,       3000,          2000 from dual
    select  region, area,
    max(case extract(month from to_date(yearmonth,'yyyymm')) when 7 then sales_target
    else 0 end ) TGT_JUL
    max(case extract(month from to_date(yearmonth,'yyyymm')) WHEN 8 then sales_target
    else 0 end ) TGT_AUG
    max(case extract(month from to_date(yearmonth,'yyyymm')) WHEN 9 then sales_target
    else 0 end ) TGT_SEP
    from d
    group by  region, area
    REG ARE    TGT_JUL    TGT_AUG    TGT_SEP
    abc pqr          0       2000          0
    mnr xyz       3000          0          0
    abc xyz       1000          0          0You can copy and replicate the results for another one - actual_sales.

  • Hierarchical query with multiple roots

    Hi,
    I'm trying to write a sql query to find blocking lock in database. The idea is to get the blocker in 1st column, comma separated list of waiters in 2nd column and number of waiters in 3rd column.
    As of now i use below query to get a tree structure
    WITH lk AS
         (SELECT  blocking_session||' (Inst-'||blocking_instance || ')' blocker,
                 SID||' (Inst-'||inst_id || ')' waiter
            FROM gv$session
           WHERE blocking_instance IS NOT NULL AND blocking_session IS NOT NULL)
    SELECT     LPAD (' ', 2 * (LEVEL - 1)) || waiter lock_tree
          FROM (SELECT *
                  FROM lk
                UNION ALL
                SELECT DISTINCT 'root', blocker
                           FROM lk
                          WHERE blocker NOT IN (SELECT waiter
                                                  FROM lk))
    CONNECT BY PRIOR waiter = blocker
    START WITH blocker = 'root';
    Result:-
    ===========
    LOCK_TREE
    1966 (Inst-1)
      908 (Inst-1)
      1906 (Inst-1)
      1900 (Inst-1)
    981 (Inst-1)
      921 (Inst-1)
      937 (Inst-1)
      962 (Inst-1)
      1889 (Inst-1)
      1904 (Inst-1)
      974 (Inst-1) But what i expect is like below. My below query works when there is only one root blocker, but fails when there are multiple root node.
    WITH lk AS
         (SELECT blocking_session || '(Inst-' || blocking_instance || ')' blocker,
                 SID || '(Inst-' || inst_id || ')' waiter
            FROM gv$session
           WHERE blocking_instance IS NOT NULL AND blocking_session IS NOT NULL)
    SELECT     blocker, SUBSTR (SYS_CONNECT_BY_PATH (waiter, ';'), 2) waiters
          FROM (SELECT   blocker, waiter, ROW_NUMBER () OVER (ORDER BY waiter)
                                                                              val
                    FROM lk
                GROUP BY blocker, waiter)
         WHERE CONNECT_BY_ISLEAF = 1
    START WITH val = 1
    CONNECT BY PRIOR val = val - 1
    Result:-
    ===========
      WAITERS# BLOCKER                                                                                 WAITERS
             3 981(Inst-1)                                                                             1904(Inst-1);921(Inst-1);937(Inst-1)
    ....lot of duplicates
    expected result:-
    ===========
      WAITERS# BLOCKER                                                                                 WAITERS
             4 981(Inst-1)                                                                             1904(Inst-1);921(Inst-1);937(Inst-1);974(Inst-1)
             3 1966(Inst-1)                                                                             908 (Inst-1);1906 (Inst-1);1900 (Inst-1) can you please help me correct above query or suggest other ways to archive this result.
    Thanks in advance
    MidhunGT

    Hi All,
    Thank you all for your support. I never knew these many ways to see blocking lock in database :)
    Somehow i was able get the desired result for my specific requirement with below query
    sql> WITH lk AS
      2       (SELECT blocking_session || ' (Inst-' || blocking_instance
      3               || ')' blocker,
      4               SID || ' (Inst-' || inst_id || ')' waiter
      5          FROM gv$session
      6         WHERE blocking_instance IS NOT NULL AND blocking_session IS NOT NULL)
      7  SELECT     blocker,
      8             LTRIM
      9                (MAX (SYS_CONNECT_BY_PATH (waiter, ','))KEEP (DENSE_RANK LAST ORDER BY cnt),
    10                 ','
    11                ) AS waiters,
    12             MAX (cnt) waiters#
    13        FROM (SELECT blocker, waiter,
    14                     ROW_NUMBER () OVER (PARTITION BY blocker ORDER BY waiter)
    15                                                                         AS cnt
    16                FROM lk)
    17    GROUP BY blocker
    18  CONNECT BY cnt - 1 = PRIOR cnt AND blocker = PRIOR blocker
    19  START WITH cnt = 1;
    BLOCKER         WAITERS                                                                            WAITERS#
    1946 (Inst-1)   1987 (Inst-1),879 (Inst-1),910 (Inst-1)                                                3
    930 (Inst-1)    1919 (Inst-1),1945 (Inst-1),1953 (Inst-1),1983 (Inst-1)                                4please advice, if any scope for improvement
    Thanks and Regards,
    MidhunGT

  • OWB - possible to use connect by prior in mappings

    Hi,
    We get data supplied in hierarchical table and like to populate column on downstream table with level in hierarchy (parent, child or grandchild).
    In sql can use connect by prior.
    Is it possible to use this in mapping?
    Thanks

    Check this:
    https://blogs.oracle.com/warehousebuilder/entry/connect_by_in_owb_10gr2_hierar

  • Deletion of duplicates in the table with out using rowid

    How can I delete duplicates in the table with out using ROWID .

    hi
    sleect count(coulmnname),columnname from table
    group by columnname
    having count(columnname) > 1;
    find the primary key of the table
    apply the below query
    delete from table
    where (primary key,repeated column name )
    not in
    ( select min(primary key), repeated column
    from employee group by repeated column );
    use this in the primary key column use empid ,,,the repated column is ename
    empid ename
    1 sankar
    2 sankar
    try this one

  • Analytical reports with out using BI poss ?

    Hi,
    Got a query
    Can we develop any analytical reports on portal which access the data directly from R/3 with out using BI. And it will provide the front end report as it has been already designed.?
    Cheers
    *RAJ*

    Hi,
    You can also use a Character variable as a msg as follows;
    Data : lv_msgtxt(100) type C.
    Concatenate 'Email not found for vendor' ':' gv_lifnr into lv_msgtxt Separated by space.
    Message lv_msgtxt Type 'S'.
    Regards
    Karthik D

  • How Achieve timedseries calculations with out using AGO And ToDate function

    Hi,,
    1)
    How Achieve timedseries calculations with out using AGO And ToDate functionion
    this question asking in interview ..is it possible..?
    if yes please response as soon as possible..
    2) i have 2 cloumns Product and value...
    client requirement is they need ranks based on Value ..in dashboard .using dashboard prompt..edit box...if user enter any number (ex :5 ) report should show top 5 ranks if he enter 20 should be top 20 ranks..
    how to achive this ?
    thanks,
    raj

    Consider yor first question:
    1. Yes, we can create timeseries measures without using AGO and TODATE
    1. Create ALIAS of fact tabe in the physical layer
    2. Join the Time id from the ALIAS fact table with the YAGO_MONTH_ID column from your time dimension table (For calculating Year Ago variants) similarly join with MAGO_MONTH_ID column for Month Ago measures.
    3.Pull the ALIAS tables as an additional Logical table source in the Lgical layer
    4.Keep the mapping of the columns from the ALIAS table as its is
    5. For e.g If you pick Revenue from the Year Ago Alias table it will give you the "Prior Year Revenue"
    See if this helps you

Maybe you are looking for