Hierarchical query to combine two groupings into one broad joint grouping

Hi there,
I would like to know if anyone knows a way to solve the problem below with a SQL querie, maybe using some hierarchical queries or window functions (or anything else in SQL for that matter).
My environment is:
Oracle Database 11g Release 11.2.0.2.0 - 64bit
The problem is this:
I have a list of items that are grouped together in two different grouping ways (two columns).
This gives the ability for items to be linked to other items in two ways:
1. Directly if both have same value on GROUP1 and/or GROUP2;
2. indirectly if they have an item in common with at least one match on either GROUP1 or GROUP2.
The idea is to start from this dataset:
WITH T AS
  SELECT 1 AS ITEM_ID, 'A' AS GROUP1, 100 AS GROUP2 FROM DUAL UNION
  SELECT 2 AS ITEM_ID, 'A' AS GROUP1, 100 AS GROUP2 FROM DUAL UNION
  SELECT 3 AS ITEM_ID, 'A' AS GROUP1, 101 AS GROUP2 FROM DUAL UNION
  SELECT 4 AS ITEM_ID, 'B' AS GROUP1, 100 AS GROUP2 FROM DUAL UNION
  SELECT 5 AS ITEM_ID, 'B' AS GROUP1, 102 AS GROUP2 FROM DUAL UNION
  SELECT 6 AS ITEM_ID, 'C' AS GROUP1, 103 AS GROUP2 FROM DUAL UNION
  SELECT 7 AS ITEM_ID, 'D' AS GROUP1, 101 AS GROUP2 FROM DUAL
SELECT * FROM T;
And end up with this dataset with a one single joint grouping:
WITH T AS
  SELECT 1000 AS JOINT_GROUP_ID, 1 AS ITEM_ID FROM DUAL UNION
  SELECT 1000 AS JOINT_GROUP_ID, 2 AS ITEM_ID FROM DUAL UNION
  SELECT 1000 AS JOINT_GROUP_ID, 3 AS ITEM_ID FROM DUAL UNION
  SELECT 1000 AS JOINT_GROUP_ID, 4 AS ITEM_ID FROM DUAL UNION
  SELECT 1000 AS JOINT_GROUP_ID, 5 AS ITEM_ID FROM DUAL UNION
  SELECT 1000 AS JOINT_GROUP_ID, 7 AS ITEM_ID FROM DUAL UNION
  SELECT 2000 AS JOINT_GROUP_ID, 6 AS ITEM_ID FROM DUAL
SELECT * FROM T;The relationships are:
Item 1 is linked to Item 2 by GROUP1 and GROUP2;
Item 1 is linked to Item 3 by GROUP1 only;
Item 1 is linked to Item 4 by GROUP2 only;
Item 1 is linked to Item 5 through Item 4 by GROUP1;
Item 1 is linked to Item 7 through Item 3 by GROUP2;
Item 6 is not linked to any other item since it does not match on GROUP1 nor GROUP2 with any other item.
NOTEs:
- JOINT_GROUP_ID values could be any sequential value. I used 1000 and 2000 just to avoid confusion with the other IDs and group values used to picture the problem.
- The level of relationship is not restricted to 2 like the example above. There could be deeper relationships.
This seems to me like something that could be solved with a hierarchical query, but I could not get my head around it to solve the problem.
Hope one of you guys can help me on this.
Chears.

Hi Bruno,
You are correct. Frank's solution does not work. You can do this using CONNECT BY on smaller problems, but it will be very inefficient for larger problems wirth significant looping. I wrote a quick blog article on this subject after reading your question this morning. This is actually an example of a very general class of problems and I already had three SQL solutions. I'll put the CONNECT BY one here, and you can look at my blog if you want more details (I include a diagram so I can't just post it here).
Data
item_groups
SQL> SELECT *
  2    FROM item_groups
  3  /
ITEM_ID    GROUP1                         GROUP2
01         A                              100
02         A                              100
03         A                              101
04         B                              100
05         B                              102
06         C                              103
07         D                              101
08         E                              104
09         E                              105
10         F                              106
10 rows selected.Query
WITH links_v AS (
SELECT t_fr.item_id node_id_fr,
       t_to.item_id node_id_to,
       t_fr.item_id || '-' || Row_Number() OVER (PARTITION BY t_fr.item_id ORDER BY t_to.item_id) link_id
  FROM item_groups t_fr
  JOIN item_groups t_to
    ON t_to.item_id > t_fr.item_id
   AND (t_to.group1 = t_fr.group1 OR t_to.group2 = t_fr.group2)
), nodes_v AS (
SELECT item_id node_id
   FROM item_groups
), tree AS (
SELECT link_id, CONNECT_BY_ROOT (link_id) root_id
  FROM links_v
CONNECT BY NOCYCLE (node_id_fr = PRIOR node_id_to OR node_id_to = PRIOR node_id_fr OR
                     node_id_fr = PRIOR node_id_fr OR node_id_to = PRIOR node_id_to)
), group_by_link AS (
SELECT DISTINCT Min (root_id) OVER (PARTITION BY link_id) group_id, link_id
  FROM tree
), linked_nodes AS (
SELECT g.group_id, l.node_id_fr node_id
  FROM group_by_link g
  JOIN links_v l
    ON l.link_id = g.link_id
UNION
SELECT g.group_id, l.node_id_to
  FROM group_by_link g
  JOIN links_v l
    ON l.link_id = g.link_id
SELECT l.group_id "Network", l.node_id "Node"
  FROM linked_nodes l
UNION ALL
SELECT '00 (unlinked)', node_id
  FROM nodes_v n
WHERE n.node_id NOT IN (SELECT node_id FROM linked_nodes)
ORDER BY 1, 2Output
Network       Node
00 (unlinked) 06
              10
01-1          01
              02
              03
              04
              05
              07
08-1          08
              09

Similar Messages

  • How do I combine two regents into one in Logic Pro Arrange?

    how do I combine two regents into one in Logic Pro Arrange?

    Thanks for your input kcstudio. I would still be left with 2 regions although one after the other, on one track.
    I am trying to save steps of the way I am combining the info of 2 seperate regions into one: bouncing the 2 tracks then re-importing that audio back into the project. It would save a lot of time if you could just drag one region on top of the other
                                W.W.

  • Combining two messages into one

    Hello,
    I have a mapping issue, I have a business process in which I have to combine two messages into one.
    To do so, I have defined a message mapping in which there are two source message types, and one target message type.
    When testing the message mapping in the IR, it works fine, but when I define and test an interface mapping with that same message mapping, I receive this error message:
    "Cannot produce target element /ns0:Messages/ns0Message1/MY_IDOC_TYPE/MY_SEGMENT. Check xml instance is valid for source xsd and target-field mapping fulfills requirements of target xsd."
    What am I doing wrong ?
    How am I supposed to combine two messages into one ?
    Thanks,
    Elad.

    Hi Elad,
    Just see if you have included both you source message interfaces and one target nessage interface correctly in while doing your interface mapping.....
    The most common mistake made when we do scenarios which include combination of two source message types into one target type are:
    - we forget to include both the source message interfaces.
    - or we interchange between one of the source message interface with the target.
    Just see if either of the 2 is aplicable in your case and just activate all components as and when you create them..
    Regards,
    abhy

  • HT4759 How do I combine two accounts into one

    How can I combine two accounts into one account

    If you are talking about iCloud accounts, you can't.
    Or you could tell us what type of accounts these are?

  • How to Combine two queries into One

    Hi Gurus,
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    SQL>
    I have following two queries. How I can convert these two queries into one with the same result ?
    Q1
    SELECT id,vdate,vendorname,venddate,vid
    FROM VENDOR
    WHERE processid=32
    AND venddate is null
    AND vid in(select vid from view_vid where type='PDX')
    AND (id,vdate) not in (select id,vdate from vkfl_is where task_id=55)
    AND (id,vdate) in (select id,vidate from market_data where marketed_date is null)
    AND id not in (select id from location)
    Q2
    SELECT id,vdate,vendorname,venddate,vid
    FROM VENDOR
    WHERE processid=20
    AND venddate is null
    AND vid in(select vid from view_vid where type='PBX')
    AND (id,vdate) not in (select id,vdate from vkfl_is where task_id=40)
    AND (id,vdate) in (select id,vidate from market_data where region_date is null)
    AND id not in (select id from location)
    I can UNION these two queries, but, is there any way I can write a single query with which gives me same result as above two queries?
    Any help would be highly appreciated
    Thanks in advance

    Hi,
    You can do something like this, which will be more efficient than a UNION:
    SELECT  id, vdate, vendorname, venddate, vid
    FROM  vendor
    WHERE  (   (    -- Conditions that apply only to q1
                               processid = 32
                AND  vid       IN (SELECT vid FROM view_vid WHERE type = 'PDX')
                AND (id,vdate) NOT IN ( SELECT id, vdate
                                        FROM   vkfl_is
                                        WHERE  task_id = 55
                AND (id,vdate) IN ( SELECT id, vidate
                                    FROM   market_data
                                    WHERE  marketed_date IS NULL
            OR  (  -- Conditions that apply only to q2
                     processid = 20
                AND  vid       IN (SELECT vid FROM view_vid WHERE type = 'PBX')
                AND (id,vdate) NOT IN ( SELECT id, vdate
                                        FROM   vkfl_is
                                        WHERE  task_id = 40
                AND (id,vdate) IN ( SELECT  id, vidate
                                    FROM  market_data
                                    WHERE  region_date IS NULL
                   -- The remaining conditions apply to both q1 and q2
    AND     venddate   IS NULL
    AND     id         NOT IN (SELECT id FROM location)
    I hope this answers your question.
    If not, post  a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Combining two tables into one result

    Hi all, I am fairly inexperienced with Crystal but have gained good results from the reports I have created, I am fluent in SQL and Basic to an extent.  I am interigating a Pronto database and I want concatenate two tables into one report.
    Table One: Customer Orders
    Fields:  Customer No, Invoice Number, Invoice date, Invoice Amount, Cost Amount.
    Table Two: Archived Customer Orders
    Fields:  Customer No, Invoice Number, Invoice date, Invoice Amount, Cost Amount.
    I want to complete a report that will tell me the sales for a given period and the outstanding orders for each customer total for all fields in each table combined into one figure.
    Any help would be greatly appreciated.
    Thanks in advance

    Hi Grant,
    As you said you are goot at writing SQL, in Crystal write a SQL statement in Add Command to join both table using Union / Union all
    If you use Union then it will filter duplicate records and pull the data from database, If you use Union All then it will include all your duplicate records.  Please use Union / Union All as required.
    Once you get all data into the report create a parameter for date range and generate the summaries as required.
    Thanks,
    Sastry

  • Question - how do I combine two users into one?

    I have migrated a lot of data to a MacBook Pro using Migration Assistant, in the process two users have been created on the Mac. How do I combine the two users into one?

    You don't. Just log in with one, choose Go to Folder from the Finder's Go menu, provide /Users/ as the path. and drag the folder there; you'll need to provide an administrator password at some point.
    (108352)

  • How do I combine two arrays into one?

    I am trying to combine two byte arrays into one. What function do I use that will put in the information in the same order just combined?

    battler. wrote:
    Julien,
    Used LV for years.  Never knew that (concatenate inputs).  Wouldn't believe the lengths ive used to get around it.  Thanks
    Same here! I actually learned about it taking a sample test for the CLAD.
    Richard

  • How to combine two albums into one

    I imported into iTunes two Shostakovich compositions so that I could burn a CD-R that contained these two works. The CD burning went fine, but iTunes insists on separating the two compositions into two albums in the display of all albums. I have made sure that the album titles and the artists displayed under the album icons are identical, but still the two will not meld into one. Will someone help me with this? I am using iTunes 9.2.1(4).

      On the "Get Information" windows (reached with right clicks) of the two separated albums, one album was marked as "no" on the "part of a compilation" option and the other was marked "yes". I changed the "no" to a "yes" and they merged. I'm not sure if I got this from the site you gave me or if I just stumbled on to it. Either way, I thank you for your kind responses.

  • Can I combine two objects into one?

    Hi all:
    I got a problem here: I just wonder if anyone knows how to combine the informations which I grabed from a SQL database to an object I obtained from an OO database at runtime.
    I look forward to your reply and appreciate your concern!
    regards
    David
    at [email protected]

    Thanks for you reply, but the combined two objects can not be pre-defined because it is defined at runtime, say, there are a number of objects in database, only when you select the one for combining, you know what it is!
    Cheers
    David

  • Can Time Machine combine two HDs into one big one?

    I know Mountain Lion added the ability to use multiple HDs simultaneously (I have done this). As it stands, it just rotates among the different HDs each time it does a backup. Is there a way to have OSX combine two HDs to make a 'virtual' bigger HD?
    The reason I ask this is because my existing iMac has a 1TB internal hard drive. I have two external LaCie drives of 2 TB each that I use for Time Machine. I'm planning on getting one of the new iMacs and custom-ordering it with a 3TB internal drive. Obviously a 2TB drive won't fit, but if OSX can combine the two HDs virtually, it'll end up with a 4TB volume, right? Can it do that?

    A hardware RAID is as reliable as the hardware. I believe the LaCie product you mention is a hardware RAID. I have no opinion of its reliability, and I don't know whether you can configure it as a mirrored RAID.
    Maybe I should clarify. I see no reason to use a RAID for backup unless you need the space. If you need a 6 TB Time Machine volume, you have to use a RAID -- striped, not mirrored. For the safety of your data, regardless of the amount, you need redundant backups, not RAID. That is, you should have at least two independent backups, at least one of which is off site at all times.

  • Combine two clips into one

    Hi, is it possible to take two clips and join them together (that were never joined before, but are two different clips)? I want to make it so both clip appear when viewed. For example, if I had a video clip of it raining outside and a clip of somebody dancing, I would want both clips to be joined into one which would be viewed as somebody dancing in the rain. I am not sure if this is possible, but any thoughts or tips would be appreciated.
    Note: (I do know that there is an effect for rain)
    Thank you!
    -Jason

    Jason,
    the effect you are looking for is called 'blue-' or 'green-screening'. The name derives from the background color you shoot one scene with. It is was usually blue because it is a color that does not appear naturally on an actor, and can easily be targeted by the composition hardware (a so-called 'chroma-keyer'. Blue worked well because at that time a simple high-pass filter on the blue channel could be used to trigger the composition circuit, and allowed real-time composition on analog hardware).
    It basically works like this:
    1. Set up a really good lit stage with a blue or green background. It is very important that both background and actor are well lit.
    2. Film your scene
    3. Film the scene you want to place your actor in (e.g. rain) - let's call it the 'actless' scene because no acting happens
    4. Use a chroma keying plug-in ('blue-screen', 'green-screen') to replace anything blue or green in your acted scene with the actless scene.
    If you have both scenes shot already (without a uniformly colored background), this will not work.
    We do have chroma-keying plug-ins (see here:
    http://www.imovieplugins.com/plugs/chromamovie.html
    and here: http://www.imovieplugins.com/plugs/chromastatic.html), but currently (while Apple is transitioning to Intel) they have become unreliable. Some of our esteemed competitors have similar plug-ins you might want to look at.
    Hope this helps,
    -ch
    Please Note:
    I work for cf/x, and may profit from posting here.

  • Combining two queries into one query if possible

    Hi there. I would like, if possible, to somehow combine the queries 1) and 2) into a single query.
    1) select distinct user_id from system_user_sessions;
    This query returns all unique users from the indicated table.
    2) select count(session_id) from system_user_sessions where user_id = "each user_id returned from 1)";
    This query will return, for each distinct user_id, the number of sessions involving that user. In other words I would like to return the user_id of each user together with the number of session_ids involving that user.
    any ideas? Joe

    I assume you are looking for something like this:
    select count(session_id)
      from system_user_sessions
    where user_id in ( select distinct user_id
                          from system_user_sessions
                      );HTH
    Ghulam

  • Combine two graphs into one graph

    Hello there! Ive posted a similar question a week back, and ive tried to do so using the suggested way, but so far my efforts are failed. Can someone please help me. Here i attached the .vi data for the program ive made.
    my only problem is, i have two curves so far Current curve and Voltage curve. I need another additional graph where in it there are 2 curves together - both current and voltage.
    I tried using 2d arrays but i got a warning message saying my input datas are not coherent. someone help. Im still new in this and i dont know what else to do.
    Thanks so much
    Attachments:
    DAS_Schleife_kleben_Gruppe1.vi ‏228 KB

    This should work.
    Tim
    Johnson Controls
    Holland Michigan
    Attachments:
    DAS_Schleife_kleben_Gruppe1.vi ‏226 KB

  • Is there a way to combine two accounts into one?

    I have an account for itunes and an account for my iphone.  The problem is I need to change my itunes account email address and it will not let me.  I do not have access to that email account any longer.  I do not want to lose my itunes and programs that I have already paid for under the email address I do not have access to any more.  How can I attach it to my other account?

    You cannot merge two Apple IDs. You cannot share purchases with other Apple IDs although there is a temporary form of sharing.
    iTunes- How to share music between different user accounts on a single computer
    Understanding Home Sharing
    iOS- Setting up Home Sharing on your iOS device
    iTunes- Setting up Home Sharing on your computer
    Setting up Home Sharing for Apple TV (2nd & 3rd generation)

Maybe you are looking for