Hierarchical query with many-to-many relationship

I have read with interest the creative solutions to complex hierarchical queries posted previously; they have been instructive but have not quite addressed this scenario.
We have a hierarchy table H, with columns for ID, name, parentID, and other attributes.
Within this table are a number of independent hierarchies, each existing for a different purpose.
We have a master list of hierarchies in table T which describes the purpose of each hierarchy, provides some default attributes which the nodes can inherit, and stores a unique id for each hierarchy and a pointer to the root node of the corresponding hierarchy in table H.
We have a master list of items M, with identically named columns to those in H, along with many other attributes.
The members of table M ALL belong to EACH of the Hierarchies. So we have a link table I to define the intersection of H and M.
So the leaf nodes of H are really containers for the list of elements from M which may be attached to them.
The universe of M is very volatile, with new members being added, old ones deleted, and existing ones being reclassified frequently from node to node within each hierarchy. Since the hierarchies have to be built to handle every possible scenario, so that the members of M can always find a suitable node to reside in, quite often, in fact more often than not, the majority of leaf nodes for each hierarchy are empty at any given moment.
Therefore, although we always know the root sector of a given hierarchy and can traverse downwards from there, if we worked our way up from the intersection table, we could eliminate up to 70% of the nodes of any given hierarchy from further consideration, as they don't need to be (in fact, must not be) included in reports.
As implied by the above, rows in M are structurally similar (in terms of columns, but not in any real world sense) and are a superset of rows in H. But combining them into the one table doesn't seem to help the reporting process due to the many-to-many relationship which prevents the ID/parentID relationship from being carried through to this level.
There are a number of other considerations of which the most pertinent is that the people using this database generally have an interest in only a subset of the master list of items in M. This relationship is also dynamic but important enough and rigid enough that another link table P exists to combine the Users in table U with the subset of M in which they are interested. (The users are also grouped into hierarchies of a totally different nature, but this aspect is secondary for now.)
The reporting is reasonably straightforward for any single combination of User and Hierarchy; they want to see all the items they are interested in, listed in hierarchical sequence, totalled on change of level with the individual items M listed beneath the nodes of H. This is unfortunately required in real time, so retrieval performance is paramount.
Some statistics might help to determine the optimum approach:
The largest hierarchy has 10,000 nodes. The smallest about 100.
The largest would have 70% or more of its nodes unused at any point in time, and even the smallest would have 25% unused.
The hierarchies tend to be broad rather than deep, the maximum number of levels being about 5; but the larger ones should be twice as deep as this if performance was not compromised.
There are dozens of hierarchies, but it may be possible to sharply reduce this number by exploiting the Order Siblings By clause.
The number of rows in M varies between 500,000 and 50,000; depending upon how long historical data is retained on-line (and performance permitting, it would be retained indefinitely).
The number of users varies between 1000 and 2000 but the range of M in which they are interested varies greatly; from as few as 100 to as many as 10,000+. So it is almost always worth beginning by eliminating the items in which they are not interested, implying once again that the hierarchy should be traversed upwards rather than down from the root.
The current system is very old and survives by a tactic of building what are essentially materialised views of the database structure for each user overnight using, ahem, non-relational technology. This is inefficient and not easily scaled (but it works) and hence this redevelopment project needs to (a) work, and (b) work better and faster.
I am happy to provide some DDL scripts if that helps explain the problem better than this narrative.
I can't help feeling that the solution lies in somehow extending the hierarchical query past the many-to-many link table so that the Master list can be merged directly into the hierarchy such that the M items become the leaf nodes rather than the design outlined above - but I don't know how to do that. But I am sure everyone reading this does! :)
All advice appreciated. Database version is not an issue; we are currently using version 10XE for experimentation, but production usage could be on 11 if that contains helpful features.
Thank you
CS

Hi,
ChrisS. wrote:
I am happy to provide some DDL scripts if that helps explain the problem better than this narrative.Yes, please do.
The problem seems interesting, I'm sure many people here (including myself) are willing to help you in this matter.
So yes, post DDL for the tables, as well as INSERTs to populate them with representative data. Please also include the output you require along with detailed explanations about the logic to get it.
Don't forget to put lines of code between {code} tags in order to preserve formatting and readability, like this :
SELECT sysdate FROM dual;Thanks.

Similar Messages

  • 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
    ;

  • Hierarchical query with where clause

    Hi,
    How can I query hierarchically a query with WHERE clause? I have a table with three fields session_id,id and root_id.
    When I try with the following query,
    select id, level from relation
    where session_id = 79977
    connect by prior id = root_id start with id = 5042;
    It gets duplicate values.
    I want the query to show in the hierarchical manner with a filter condition using WHERE clause. Please help me how can I achieve this. If you know any link that describes more about this, please send it.
    Thanks in Advance.
    Regards,
    -Parmy

    Hi Sridhar Murthy an others,
    Thanks a lot for your/the answer. It's working for me. It saved a lot of other work around without the proper knowledge of hierarchical query. Please send me any link that describes these issues in detail and also I hope as I have mentioned in the other message, same cannot be achieved on views or ( on two different tables ???)
    Any way thanks for your reply,
    It's working for me.
    With happiness,
    -Parmy

  • 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

  • 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.

  • Recursive Hierarchical Query with CONNECT BY/START WITH

    I want to traverse a tree which has is not hierarchical in linear sense. You know, like :
    A
    B
    C
    D
    E
    C
    F
    D
    E
    C
    You see that D, Eand C are repeated and C is under E as well as under B. I tried using CONNECT BY and START WITH but I get tripliate occurances of C under B, and 2 occurances of DEC under A and under F. Clearly this is not correct. I believe SQL3 has special way of handling with such recursive trees. How does O9i handle these constructs? Please help.

    CREATE OR REPLACE PACKAGE hierarchy
    IS
      TYPE branchtable_type IS TABLE OF VARCHAR2 (4000)
      INDEX BY BINARY_INTEGER;
      branchtable branchtable_type;
      FUNCTION branch
        (v_level     IN NUMBER,
         v_value     IN VARCHAR2,
         v_delimeter IN VARCHAR2 DEFAULT CHR (0))
        RETURN VARCHAR2;
      PRAGMA RESTRICT_REFERENCES (branch, WNDS);
    END hierarchy;
    CREATE OR REPLACE PACKAGE BODY hierarchy
    IS
      returnvalue VARCHAR2 (4000);
      FUNCTION branch
        (v_level     IN NUMBER,
         v_value     IN VARCHAR2,
         v_delimeter IN VARCHAR2 DEFAULT CHR (0))
        RETURN VARCHAR2
      IS
      BEGIN
        branchtable (v_level) := v_value;
        returnvalue := v_value;
        FOR i IN REVERSE 1 .. v_level - 1
        LOOP
          returnvalue := branchtable (i)
          || v_delimeter
          || returnvalue;
        END LOOP;
        RETURN returnvalue;
      END branch;
    END hierarchy;
    SELECT   id, parent_id, print_order, lvl
    FROM     (SELECT     id, parent_id, print_order, LEVEL lvl,
                         hierarchy.branch (LEVEL, print_order) branch
              FROM       test_table
              START WITH parent_id IS NULL
              CONNECT BY PRIOR id = parent_id)
    ORDER BY branch
            ID  PARENT_ID PRINT_ORDER        LVL
             1                      1          1
             6          1           1          2
             5          1           2          2
             2          1           3          2
             4          2           1          3
             3          2           2          3
    6 rows selected.

  • Joins in Hierarchical Query

    I'm trying to use a Hierarchical Query with table joins in the "FROM" clause. According to the documentation, this will work with Oracle 9i and above.
    My problem is that in some queries, using the "JOIN" syntax works correctly but in others, it gives an "ORA-00928" message.
    If I change the query that gives the error to use old style Oracle joins (using the where clause), the query works.
    Can anyone help me to identify the problem?

    Here's the query. Again, note that if I use the old oracle join syntax (using where clause) it works:
    select level
    , biu.parent_part_no
    , biu.parent_part_serial_no
    , biu.comp_part_qty
    , cpi.part_no
    , cpi.serial_number
    , cpi.trace_code
    from bom.bom_instance_usage biu
    join bom.bom_part_instance cpi
    on cpi.bom_part_instance_key = iu.comp_part_instance_key
    start with ( biu.parent_part_no = '123456'
    and biu.parent_part_serial_no = '114' )
    connect by ( biu.parent_part_no = prior cpi.part_no
    and biu.parent_part_serial_no = prior cpi.serial_number )

  • QUESTION:  HOW TO WRITE QUERY  WITH MANY TO MANY RELATIONSHIPS

    Could someone help me out here?
    I was sitting here looking at some tables ie table_name and synonyms and wondering.
    If a table can belong to many synonyms and a synonym can belong to many tables how would one write a query where I would like to know which tables belong to each synonym or on the other hand which synonym belongs to what tables?
    Would I try to develop an outside join for this, a corrolated query or a query with a subquery or would there be another format that would work better?
    What would be the best method of attack on this?
    Thanks for your thoughts on this.
    al

    Actually, the relationship is not many to many. A table can have many synonyms, but a synonym within a namespace (i.e. a PUBLIC synonym, or a private synonym created by a user) can only point to one table. The xxx_synonmys tables already contain the information about the table_name and table_owner.
    John

  • How to create query for tables with many to many relationship

    in my sql i'm unable to update the table using select clause...is there any way to update a table which is in many to many relationship.
    Ex:1st table student(student_id int primary key auto_increment, student_name varchar(30));
    2nd table contact (contact_id int primary key auto_increment, c_email varchar(40));
    3rd table student_contact(student_id int references student, contact_id int references contact);
    i would like to auto insert the both two columns in the student_contact while the student and the contact table being updated automatically.

    This is a JSP/JSTL forum, not a SQL forum. If you're using MySQL, better use their own forums at dev.mysql.com.
    I'll give some hints anyway: learn about SQL JOIN. In general there is good SQL documentation available at the website of the RDBMS manfacturer. Go check it out. There is also a nice SQL tutorial at w3schools.com. Good luck.

  • Defining a many-to-many relationship with CMP EJBs  : does it work for you

    Curious to know whether someone has been able to set up a many to many relationship between two entity beans.
    I have been struggling with this for days now and I can't get it to work.
    In my test project I have two entity beans, resp. Consultant and Solution.
    Consultant has a cmr field called 'solutions', which is a collection object from the opposite side (Solution).
    This is the source of the ejb-jar.xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
    <ejb-jar>
         <description>EJB JAR description</description>
         <display-name>EJB JAR</display-name>
         <enterprise-beans>
              <session>
                   <ejb-name>ProfilerBean</ejb-name>
                   <home>com.atosorigin.tcc.testing.ejbses.profiling.ProfilerHome</home>
                   <remote>com.atosorigin.tcc.testing.ejbses.profiling.Profiler</remote>
                   <local-home>com.atosorigin.tcc.testing.ejbses.profiling.ProfilerLocalHome</local-home>
                   <local>com.atosorigin.tcc.testing.ejbses.profiling.ProfilerLocal</local>
                   <ejb-class>com.atosorigin.tcc.testing.ejbses.profiling.ProfilerBean</ejb-class>
                   <session-type>Stateless</session-type>
                   <transaction-type>Container</transaction-type>
                   <ejb-local-ref>
                        <ejb-ref-name>EJBTesting/Solution</ejb-ref-name>
                        <ejb-ref-type>Entity</ejb-ref-type>
                        <local-home>com.atosorigin.tcc.testing.ejbcmp.profiling.SolutionLocalHome</local-home>
                        <local>com.atosorigin.tcc.testing.ejbcmp.profiling.SolutionLocal</local>
                        <ejb-link>SolutionBean</ejb-link>
                   </ejb-local-ref>
                   <ejb-local-ref>
                        <ejb-ref-name>EJBTesting/Consultant</ejb-ref-name>
                        <ejb-ref-type>Entity</ejb-ref-type>
                        <local-home>com.atosorigin.tcc.testing.ejbcmp.profiling.ConsultantLocalHome</local-home>
                        <local>com.atosorigin.tcc.testing.ejbcmp.profiling.ConsultantLocal</local>
                        <ejb-link>ConsultantBean</ejb-link>
                   </ejb-local-ref>
              </session>
              <entity>
                   <ejb-name>ConsultantBean</ejb-name>
                   <home>com.atosorigin.tcc.testing.ejbcmp.profiling.ConsultantHome</home>
                   <remote>com.atosorigin.tcc.testing.ejbcmp.profiling.Consultant</remote>
                   <local-home>com.atosorigin.tcc.testing.ejbcmp.profiling.ConsultantLocalHome</local-home>
                   <local>com.atosorigin.tcc.testing.ejbcmp.profiling.ConsultantLocal</local>
                   <ejb-class>com.atosorigin.tcc.testing.ejbcmp.profiling.ConsultantBean</ejb-class>
                   <persistence-type>Container</persistence-type>
                   <prim-key-class>java.lang.String</prim-key-class>
                   <reentrant>False</reentrant>
                   <cmp-version>2.x</cmp-version>
                   <abstract-schema-name>Consultant</abstract-schema-name>
                   <cmp-field>
                        <field-name>firstname</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>lastname</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>country</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>id</field-name>
                   </cmp-field>
                   <primkey-field>id</primkey-field>
                   <query>
                        <query-method>
                             <method-name>findBySolution</method-name>
                             <method-params>
                                  <method-param>java.lang.String</method-param>
                             </method-params>
                        </query-method>
                        <ejb-ql>SELECT Object(c) FROM Consultant AS c,
                        IN(c.solutions) s WHERE s.id = ?1 </ejb-ql>
                   </query>
              </entity>
              <entity>
                   <ejb-name>SolutionBean</ejb-name>
                   <home>com.atosorigin.tcc.testing.ejbcmp.profiling.SolutionHome</home>
                   <remote>com.atosorigin.tcc.testing.ejbcmp.profiling.Solution</remote>
                   <local-home>com.atosorigin.tcc.testing.ejbcmp.profiling.SolutionLocalHome</local-home>
                   <local>com.atosorigin.tcc.testing.ejbcmp.profiling.SolutionLocal</local>
                   <ejb-class>com.atosorigin.tcc.testing.ejbcmp.profiling.SolutionBean</ejb-class>
                   <persistence-type>Container</persistence-type>
                   <prim-key-class>java.lang.String</prim-key-class>
                   <reentrant>False</reentrant>
                   <cmp-version>2.x</cmp-version>
                   <abstract-schema-name>Solution</abstract-schema-name>
                   <cmp-field>
                        <field-name>description</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>name</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>parent</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>id</field-name>
                   </cmp-field>
                   <primkey-field>id</primkey-field>
                   <query>
                        <query-method>
                             <method-name>findChildSolutions</method-name>
                             <method-params>
                                  <method-param>java.lang.String</method-param>
                             </method-params>
                        </query-method>
                        <ejb-ql>SELECT Object(s) FROM Solution AS s WHERE
                        s.parent = ?1</ejb-ql>
                   </query>
                   <query>
                        <query-method>
                             <method-name>findTopLevelSolutions</method-name>
                             <method-params/>
                        </query-method>
                        <ejb-ql>Select Object(s) FROM Solution AS s WHERE
                        (s.parent = &apos;none&apos;)</ejb-ql>
                   </query>
              </entity>
         </enterprise-beans>
         <relationships>
              <ejb-relation>
                   <description>A consultant may have one or more areas of expertise</description>
                   <ejb-relation-name>Consultant_Solutions</ejb-relation-name>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>com.atosorigin.tcc.testing.ejbcmp.profiling.ConsultantBean</ejb-relationship-role-name>
                        <multiplicity>Many</multiplicity>
                        <relationship-role-source>
                             <ejb-name>ConsultantBean</ejb-name>
                        </relationship-role-source>
                        <cmr-field>
                             <cmr-field-name>solutions</cmr-field-name>
                             <cmr-field-type>java.util.Collection</cmr-field-type>
                        </cmr-field>
                   </ejb-relationship-role>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>com.atosorigin.tcc.testing.ejbcmp.profiling.SolutionBean</ejb-relationship-role-name>
                        <multiplicity>Many</multiplicity>
                        <relationship-role-source>
                             <ejb-name>SolutionBean</ejb-name>
                        </relationship-role-source>
                   </ejb-relationship-role>
              </ejb-relation>
         </relationships>
         <assembly-descriptor>
              <container-transaction>
                   <description>container-transaction</description>
                   <method>
                        <ejb-name>SolutionBean</ejb-name>
                        <method-name>*</method-name>
                   </method>
                   <method>
                        <ejb-name>ProfilerBean</ejb-name>
                        <method-name>*</method-name>
                   </method>
                   <method>
                        <ejb-name>ConsultantBean</ejb-name>
                        <method-name>*</method-name>
                   </method>
                   <trans-attribute>Required</trans-attribute>
              </container-transaction>
         </assembly-descriptor>
    </ejb-jar>
    I created a stateless session bean as a business facade for the two entity beans. I then created a webservice to test the beans.
    What works :
    - create a consultant
    - get a consultant
    - create a solution
    - get a solution
    (basically everything that doesn't involve the relationship field.
    However, what doesn't work is the method call assignSolution:
    - assign solution : this is implemented as follows
    Business Method.
         public void assignSolution(String consultantID, String solutionID)
              throws ProfilingException {
              // TODO : Implement
              ConsultantLocal cons = null;
              SolutionLocal sol = null;
              try {
                   cons = consHome.findByPrimaryKey(consultantID);
                   sol = solHome.findByPrimaryKey(solutionID);
                   Collection solutions = cons.getSolutions();
                   solutions.add(sol);
                   //sol.getConsultants().add(cons);
              } catch (FinderException ex) {
                   ex.printStackTrace();
                   throw new ProfilingException("failed to retrieve data from DB", ex);
    As you can see I am trying to use the CM Relationship in this methhod. Adding the solution to a consultant should be as simple as adding a solution object to the collection retrieved with the getSolutions accessor. The Container is expected to persist the information in my MAXDB database.
    However this doesn't happen.
    The ORM details as defined in the persistent.xml follows :
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE persistent-ejb-map SYSTEM "persistent.dtd">
    <persistent-ejb-map>
         <locking
              type="Table"/>
         <db-properties>
              <data-source-name>TCC_PORTAL_PROFILER</data-source-name>
              <database-vendor
                   name="SAPDB"/>
         </db-properties>
         <entity-beans>
              <entity-bean>
                   <ejb-name>ConsultantBean</ejb-name>
                   <table-name>PFL_CONSULTANTS</table-name>
                   <field-map
                        key-type="NoKey">
                        <field-name>firstname</field-name>
                        <column>
                             <column-name>FIRSTNAME</column-name>
                        </column>
                   </field-map>
                   <field-map
                        key-type="NoKey">
                        <field-name>lastname</field-name>
                        <column>
                             <column-name>LASTNAME</column-name>
                        </column>
                   </field-map>
                   <field-map
                        key-type="NoKey">
                        <field-name>country</field-name>
                        <column>
                             <column-name>COUNTRY</column-name>
                        </column>
                   </field-map>
                   <field-map
                        key-type="PrimaryKey">
                        <field-name>id</field-name>
                        <column>
                             <column-name>ID</column-name>
                        </column>
                   </field-map>
                   <finder-descriptor>
                        <method-name>findBySolution</method-name>
                        <method-params>
                             <method-param>java.lang.String</method-param>
                        </method-params>
                        <load-selected-objects
                             lock="read"/>
                   </finder-descriptor>
              </entity-bean>
              <entity-bean>
                   <ejb-name>SolutionBean</ejb-name>
                   <table-name>PFL_SAPSOLUTIONS</table-name>
                   <field-map
                        key-type="NoKey">
                        <field-name>description</field-name>
                        <column>
                             <column-name>DESCRIPTION</column-name>
                        </column>
                   </field-map>
                   <field-map
                        key-type="NoKey">
                        <field-name>name</field-name>
                        <column>
                             <column-name>NAME</column-name>
                        </column>
                   </field-map>
                   <field-map
                        key-type="NoKey">
                        <field-name>parent</field-name>
                        <column>
                             <column-name>PARENTID</column-name>
                        </column>
                   </field-map>
                   <field-map
                        key-type="PrimaryKey">
                        <field-name>id</field-name>
                        <column>
                             <column-name>ID</column-name>
                        </column>
                   </field-map>
                   <finder-descriptor>
                        <method-name>findChildSolutions</method-name>
                        <method-params>
                             <method-param>java.lang.String</method-param>
                        </method-params>
                        <load-selected-objects
                             lock="read"/>
                   </finder-descriptor>
                   <finder-descriptor>
                        <method-name>findTopLevelSolutions</method-name>
                        <method-params/>
                        <load-selected-objects
                             lock="read"/>
                   </finder-descriptor>
              </entity-bean>
         </entity-beans>
         <relationships>
              <table-relation>
                   <help-table>PFL_CONS_SOL_MAP</help-table>
                   <table-relationship-role
                        key-type="PrimaryKey">
                        <ejb-name>ConsultantBean</ejb-name>
                        <cmr-field>solutions</cmr-field>
                        <fk-column>
                             <column-name>CONSULTANTID</column-name>
                             <pk-field-name>id</pk-field-name>
                        </fk-column>
                   </table-relationship-role>
                   <table-relationship-role
                        key-type="PrimaryKey">
                        <ejb-name>SolutionBean</ejb-name>
                        <fk-column>
                             <column-name>SOLUTIONID</column-name>
                             <pk-field-name>id</pk-field-name>
                        </fk-column>
                   </table-relationship-role>
              </table-relation>
         </relationships>
    </persistent-ejb-map>
    The error in the default trace file when calling the method states, there is an "inconsistency in the number of primary keys". Details follow.
    #1.5#000F1F188E5C004400000000000010480003E76C80EFD57A#1098880364327#com.sap.engine.services.ejb#com.atosorigin.tcc/EJBCMPProfilingTest#com.sap.engine.services.ejb#Guest#2####4d2b2370281411d9a40d000f1f188e5c#SAPEngine_Application_Thread[impl:3]_31##0#0#Error##Java###
    [EXCEPTION]
    #1#com.sap.engine.services.ejb.exceptions.BaseRemoteException: Exception in method assignSolution.
         at com.atosorigin.tcc.testing.ejbses.profiling.ProfilerObjectImpl0.assignSolution(ProfilerObjectImpl0.java:822)
         at com.atosorigin.tcc.testing.ejbses.profiling.Profiler_Stub.assignSolution(Profiler_Stub.java:533)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at com.sap.engine.services.ejb.session.stateless_sp5.ObjectStubProxyImpl.invoke(ObjectStubProxyImpl.java:187)
         at $Proxy73.assignSolution(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at com.sap.engine.services.webservices.runtime.EJBImplementationContainer.invokeMethod(EJBImplementationContainer.java:126)
         at com.sap.engine.services.webservices.runtime.RuntimeProcessor.process(RuntimeProcessor.java:146)
         at com.sap.engine.services.webservices.runtime.RuntimeProcessor.process(RuntimeProcessor.java:68)
         at com.sap.engine.services.webservices.runtime.servlet.ServletDispatcherImpl.doPost(ServletDispatcherImpl.java:92)
         at SoapServlet.doPost(SoapServlet.java:51)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:385)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:263)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:339)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:317)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:810)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:238)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:92)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:147)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:37)
         at com.sap.engine.core.cluster.impl6.session.UnorderedChannel$MessageRunner.run(UnorderedChannel.java:71)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:94)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:162)
    Caused by: com.sap.engine.services.applocking.exception.SAPAppLockingIllegalArgumentException: Inconsistency in number of primary keys
         at com.sap.engine.services.applocking.TableLockingImpl.getArgument(TableLockingImpl.java:385)
         at com.sap.engine.services.applocking.TableLockingImpl.lock(TableLockingImpl.java:128)
         at com.sap.engine.services.applocking.TableLockingImpl.lock(TableLockingImpl.java:138)
         at com.sap.engine.services.ejb.entity.pm.lock.TableLockingSystem.write(TableLockingSystem.java:82)
         at com.sap.engine.services.ejb.entity.pm.PersistentM2M.create(PersistentM2M.java:172)
         at com.sap.engine.services.ejb.entity.pm.PersistentCacheM2M.add(PersistentCacheM2M.java:197)
         at com.sap.engine.services.ejb.entity.pm.multiple.CollectionM2M.add(CollectionM2M.java:57)
         at com.atosorigin.tcc.testing.ejbses.profiling.ProfilerBean.assignSolution(ProfilerBean.java:201)
         at com.atosorigin.tcc.testing.ejbses.profiling.ProfilerObjectImpl0.assignSolution(ProfilerObjectImpl0.java:771)
         ... 32 more
    I can't figure out what the problem is with the ORM mapping defined.
    On the database level I have three tables. Consultant maps to PFL_CONSULTANT, Solution to PFL_SAPSOLUTIONS. The third table PFL_CONS_SOL_MAP is the help table used for the relationship (having two fields, which are in fact foreign keys from the other two tables to express the assignment of solutions to consultants (where a consultant can have one or more solutions).
    ps. : I am running Netweaver Developer Workplace (Netweaver 2004, at stack level 5)
    Message was edited by: Theo Paesen

    Hm, after disabling 'automatic locking' it works.

  • Find many-to-many relationship between two columns in one query

    Hi All,
    How can I run one query to determine if Column1 and Column2 in the following table have a many-to-many relationship?
    Column1
    Column2
    Column3
    b
    x
    s
    b
    x
    t
    c
    x
    s
    c
    y
    s
    c
    y
    t
    Just by eyeballing it, we know there is, but in a real life situation, you cannot eyeball millions of records to make that decision.
    I am using Access 2007.  (SQL script that works with Access 2007 will be great, but script for SQL Server will be fine too.)
    BI Analyst

    Hi BI Analyst,
    Take a look at this code:
    IF OBJECT_ID('tempdb..#experiment') IS NOT NULL DROP TABLE #experiment;
    CREATE TABLE #experiment (c1 CHAR(1), c2 CHAR(1), c3 CHAR(1))
    INSERT INTO #experiment (c1,c2,c3) VALUES ('b','x','s'),('b','x','t'),('c','x','s'),('c','y','s'),('c','y','t')
    SELECT c1, c2, c1+c2 AS bind,
    COUNT(c1) OVER (PARTITION BY c1+c2) c1perbind,
    COUNT(c2) OVER (PARTITION BY c1+c2) c2perbind,
    COUNT(c1+c2) OVER (PARTITION BY c1) bindsperc1,
    COUNT(c1+c2) OVER (PARTITION BY c2) bindsperc2
    FROM #experiment
    What your question asks is if there can be determined a many-to-many relationship. A many-to-many relationship is logical relation comprised of a pair of one-to-many relationships. The code above shows you which relational pairing occur in these one-to many
    relationships. c1perbind (or c2) >1 indicates a one to many relation from that relational pairing, whereas the bindsperc1 indicates how many relations the individual c1 belongs to.
    Now look at this code:
    SELECT c1, c2, bind,
    COUNT(c1) OVER (PARTITION BY c1+c2) c1perbind,
    COUNT(c2) OVER (PARTITION BY c1+c2) c2perbind,
    COUNT(bind) OVER (PARTITION BY c1) bindsperc1,
    COUNT(bind) OVER (PARTITION BY c2) bindsperc2
    FROM (SELECT DISTINCT c1, c2, c1+c2 AS bind FROM #experiment ) Q1
    With the subquery reducing the set for the windows to operate on to distinct pairs the bindsperC1 and bindsperC2 will show count greater than one if they belong to a one-to-many relationship. When both are greater than 1 those rows are proof that the relationship
    between C1 and C2 is a many-to-many.
    If you're happy and you know it vote and mark.

  • Aggregating across many-to-many relationship in Power Query?

    Hi, another M question.
    I am trying to push all my DAX calculated column logic back to Power Query and what I couldn't figure out is how to aggregate across my many to many relationship.
    Customer has many companies. He has sales for each company on a bunch of dates. Also, he has timesheets for each company for each date. Customer would like to calculate the labour cost for each company and show them as a ratio of sales in the sales report.
    (eg Kitchen labour cost should be x% of food sales)
    Now I am fine writing all the measures in DAX because I can put them in a table isolated from the Power Query tables. But calculated columns I would ideally push back to Power Query. 
    This is the DAX I constructed to put a calc column in the SalesReport table for the Kitchen labour costs
    =CALCULATE(SUM(Timesheet[Labour Cost]), FILTER(Bridge_CompanyDate, Bridge_CompanyDate[CompanyDateKey]=SalesReports[CompanyDateKey]), FILTER(Timesheet, Timesheet[Category]="Kitchen"))
    Is there a way to do similar types of aggregation in Power Query? I am tired of rewriting these calc columns when I have to reload the thing in the data model :(
    Thanks

    Hi Cathy. You can do this kind of calculation in Power Query, but it's not quite the same as in Power Pivot/DAX.
    If I understand your DAX expression correctly, you're wanting the sum of the [Labour Cost] column from the Timesheet table, for all rows with a [Category] of "Kitchen", where the timesheet date matches the date of the current row in the SalesReport table.
    In M, this would look something like this:
    = Table.AddColumn(Source, "Kitchen Labour Cost", each let expectedDate = [Date] in List.Sum(Table.SelectRows(Timesheet, each [Category] = "Kitchen" and [Date] = expectedDate)[Labour Cost]))
    (Instead of going through the Bridge_CompanyDate table, I'm matching the SalesReport and Timesheet dates directly just to make the example simpler.)
    Let me know if that helps.
    Ehren

  • Working with many-to-many relationships

    I am about to start my first experience with many-to-many
    relationships using PHP and MySQL.
    My project is to create an events registration form. As you
    know, there can be many events and many participants attending many
    events.
    I am not sure on how to structure my database and tables so I
    will first show you what I have:
    create table programs (
    program_id int not null primary key auto_increment,
    program_name varchar(100) not null,
    program_date varchar(25) not null,
    program_time varchar(25) not null,
    program_coordinator varchar(100),
    program_seats int not null
    create table participants (
    participant_id int not null primary key auto_increment,
    participant_name varchar(100) not null,
    participant_phone varchar(12) not null
    I know that I need a middle table to join the two.
    create table programs_participants (
    program_id int references program(id),
    participants_id int references participants(id),
    primary key (program_id, participants_id)
    My problem is, how do I submit to both the participants AND
    the programs_participants table together? Or is this not possible?
    The participants are not already in the database when we register
    them. We enter their personal info and select their desired events
    from checkboxes on the same page.
    Thanks for your help.

    > My problem is, how do I submit to both the participants
    AND the
    > programs_participants table together? Or is this not
    possible? The
    > participants are not already in the database when we
    register them. We
    > enter
    > their personal info and select their desired events from
    checkboxes on the
    > same
    > page.
    What you need to do is a multi-step insert.
    First, you insert the new participant into the participant
    table, then use
    the @@identity command to get the uniqueID of that newly
    entered record.
    Then you can take that uniqueID to build the entry for the
    programs_participants table.
    If you use a stored procedure, you should be able to do all
    of that with
    only having to create one call to the DB from your
    Application.
    _Darrel

  • How to write sql query with many parameter in ireport

    hai,
    i'm a new user in ireport.how to write sql query with many parameters in ireport's report query?i already know to create a parameter like(select * from payment where entity=$P{entity}.
    but i don't know to create query if more than 1 parameter.i also have parameter such as
    $P{entity},$P{id},$P{ic}.please help me for this.
    thanks

    You are in the wrong place. The ireport support forum may be found here
    http://www.jasperforge.org/index.php?option=com_joomlaboard&Itemid=215&func=showcat&catid=9

  • Dynamic List of record subsets with a Many-to-many relationship

    I'm feeling pretty lost here and would appreciate any pointers.
    I'm trying to use ADDT to create a dynamic list of records that includes a subset of comma separated list of many-to-many related records. Specifically I'm listing a bunch of workshops that have various teachers associated with each workshops. Teachers team teach a variety of workshops, thus the need for a many-to-many link table.
    I've created a basic query to retrieve the workshop list, then another query to return the teacher's associated with the workshops. However I can't figure out how to use ADDT to list the teachers for each workshop.
    I have a sense that it has something to do with a nested repeat region but there does not seem to be a way to get the wizard to see beyond the link table.
    Am I way off here?
    Thanks!

    Hi,
    a list used in the singleSelectOne component does not change or set the currency in the list VO (in opposite to the navigation list). So this synchronization needs to be done programmatically. Examples of dependent list of values are available here
    --> example 62 http://radio.weblogs.com/0118231/stories/2004/09/23/notYetDocumentedAdfSampleApplications.html
    --> word document you can download from http://thepeninsulasedge.com/frank_nimphius/2008/05/16/blogbuster-treasures-hunt-blog-entries-from-the-lost-orablogs-blog-for-download/
    Frank

Maybe you are looking for