Hierarchical Query Child OverrideInserting multiple rows in a single SQL query?How do I limit the number of rows returned by an Oracle query after ordering?one-to-many query selecting all parents and single top child for each parentReplace Default Null Values Returned From Left Outer JoinJoin vs. sub-queryHow to query MongoDB with “like”?What are the options for storing hierarchical data in a relational database?Joins: How to Return default values for empty right side of left outer joinreturn null if no rows found oracle query with IN clauseHQL Left outer join with temp tables

Suffocation while cooking under an umbrella?

A file manager to open a zip file like opening a folder, instead of extract it by using a archive manager

What is the difference between an astronaut in the ISS and a freediver in perfect neutral buoyancy?

Fuel sender works when outside of tank, but not when in tank

Carry vs Roll-Down on a zero-coupon IRS

Is there something that can completely prevent the effects of the Hold Person spell?

Is it acceptable to say that a reviewer's concern is not going to be addressed because then the paper would be too long?

Does the Way of Shadow monk's Shadow Step feature count as a magical ability?

How to see the previous "Accessed" date in Windows

What is the white pattern on trim wheel for?

Pi Zero Work With Embedded WIFI And Cellular USB Modem

What are ATC-side procedures to handle a jammed frequency?

Strange Sticky Substance on Digital Camera

List of 1000 most common words across all languages

Can an integer optimization problem be convex?

practicality of 30 year fix mortgage at 55 years of age

How to deal with a Homophobic PC

Is it a good idea to leave minor world details to the reader's imagination?

A famous scholar sent me an unpublished draft of hers. Then she died. I think her work should be published. What should I do?

Why are there two fundamental laws of logic?

What exactly did this mechanic sabotage on the American Airlines 737, and how dangerous was it?

How do you use the interjection for snorting?

Why does this image of Jupiter look so strange?

Excel Solver linear programming - Is it possible to use average of values as a constraint without #DIV/0! errors or sacrificing linearity?



Hierarchical Query Child Override


Inserting multiple rows in a single SQL query?How do I limit the number of rows returned by an Oracle query after ordering?one-to-many query selecting all parents and single top child for each parentReplace Default Null Values Returned From Left Outer JoinJoin vs. sub-queryHow to query MongoDB with “like”?What are the options for storing hierarchical data in a relational database?Joins: How to Return default values for empty right side of left outer joinreturn null if no rows found oracle query with IN clauseHQL Left outer join with temp tables






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have a hierarchical company structure where each company has an optional company sector. Child companies inherit their parent's sector if they don't have their own, but the child company sector overrides its parent's if the child one.



I need to produce a sum of the bill amount grouped by sector. Companies with no sector are ignored.



The ParentCompanyID column in the Company table is a foreign key to itself. There can be an unlimited number of parent/child levels.



Company Table



CompanyID ParentCompanyID
1 null
2 1
3 2
4 null
5 4
6 null
7 6
8 7


CompanySector Table



CompanyID Sector
1 Distribution
4 Distribution
5 Manufacturing
8 Manufacturing


Timesheet Table



CompanyID BillAmount
1 100
1 200
2 100
3 50
4 25
5 75
6 75
7 115
8 115


The result I expect to see here is:



 Sector BillAmount 
Distribution 475
Manufacturing 190


Below is how I am currently doing it. It is extremely inefficient and doesn't work for unlimited number of hierarchical levels.



WITH Company AS
( SELECT 1 CompanyID, NULL ParentCompanyID FROM dual
UNION
SELECT 2, 1 FROM dual
UNION
SELECT 3, 2 FROM dual
UNION
SELECT 4, NULL FROM dual
UNION
SELECT 5, 4 FROM dual
UNION
SELECT 6, NULL FROM dual
UNION
SELECT 7, 6 FROM dual
UNION
SELECT 8, 7 FROM dual
),
CompanySector AS
( SELECT 1 CompanyID, 'Distribution' Sector FROM dual
UNION
SELECT 4 , 'Distribution' FROM dual
UNION
SELECT 5 , 'Manufacturing' FROM dual
UNION
SELECT 8 , 'Manufacturing' FROM dual
),
Timesheets AS
( SELECT 1 CompanyID, 100 BillAmount FROM dual
UNION
SELECT 1 CompanyID, 200 BillAmount FROM dual
UNION
SELECT 2 CompanyID, 100 BillAmount FROM dual
UNION
SELECT 3 CompanyID, 50 BillAmount FROM dual
UNION
SELECT 4 CompanyID, 25 BillAmount FROM dual
UNION
SELECT 5 CompanyID, 75 BillAmount FROM dual
UNION
SELECT 6 CompanyID, 75 BillAmount FROM dual
UNION
SELECT 7 CompanyID, 115 BillAmount FROM dual
UNION
SELECT 8 CompanyID, 115 BillAmount FROM dual
),

--Dummy tables above
--My current way of doing it below
companies AS
(SELECT c.*,
cs.sector
FROM company c
LEFT OUTER JOIN CompanySector cs
ON c.companyID = cs.companyID
),
sectors AS
(SELECT levelOne.companyID,
NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) sector
FROM companies levelOne
LEFT OUTER JOIN companies levelTwo
ON levelOne.parentcompanyid = levelTwo.companyID
LEFT OUTER JOIN companies levelThree
ON levelTwo.parentcompanyid = levelThree.companyID
WHERE NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) IS NOT NULL
)
SELECT s.sector,
SUM(t.billamount)
FROM sectors s
INNER JOIN timesheets t
ON s.companyID = t.companyID
GROUP BY sector;


What is a cleaner and more efficient way of doing this?










share|improve this question






























    2















    I have a hierarchical company structure where each company has an optional company sector. Child companies inherit their parent's sector if they don't have their own, but the child company sector overrides its parent's if the child one.



    I need to produce a sum of the bill amount grouped by sector. Companies with no sector are ignored.



    The ParentCompanyID column in the Company table is a foreign key to itself. There can be an unlimited number of parent/child levels.



    Company Table



    CompanyID ParentCompanyID
    1 null
    2 1
    3 2
    4 null
    5 4
    6 null
    7 6
    8 7


    CompanySector Table



    CompanyID Sector
    1 Distribution
    4 Distribution
    5 Manufacturing
    8 Manufacturing


    Timesheet Table



    CompanyID BillAmount
    1 100
    1 200
    2 100
    3 50
    4 25
    5 75
    6 75
    7 115
    8 115


    The result I expect to see here is:



     Sector BillAmount 
    Distribution 475
    Manufacturing 190


    Below is how I am currently doing it. It is extremely inefficient and doesn't work for unlimited number of hierarchical levels.



    WITH Company AS
    ( SELECT 1 CompanyID, NULL ParentCompanyID FROM dual
    UNION
    SELECT 2, 1 FROM dual
    UNION
    SELECT 3, 2 FROM dual
    UNION
    SELECT 4, NULL FROM dual
    UNION
    SELECT 5, 4 FROM dual
    UNION
    SELECT 6, NULL FROM dual
    UNION
    SELECT 7, 6 FROM dual
    UNION
    SELECT 8, 7 FROM dual
    ),
    CompanySector AS
    ( SELECT 1 CompanyID, 'Distribution' Sector FROM dual
    UNION
    SELECT 4 , 'Distribution' FROM dual
    UNION
    SELECT 5 , 'Manufacturing' FROM dual
    UNION
    SELECT 8 , 'Manufacturing' FROM dual
    ),
    Timesheets AS
    ( SELECT 1 CompanyID, 100 BillAmount FROM dual
    UNION
    SELECT 1 CompanyID, 200 BillAmount FROM dual
    UNION
    SELECT 2 CompanyID, 100 BillAmount FROM dual
    UNION
    SELECT 3 CompanyID, 50 BillAmount FROM dual
    UNION
    SELECT 4 CompanyID, 25 BillAmount FROM dual
    UNION
    SELECT 5 CompanyID, 75 BillAmount FROM dual
    UNION
    SELECT 6 CompanyID, 75 BillAmount FROM dual
    UNION
    SELECT 7 CompanyID, 115 BillAmount FROM dual
    UNION
    SELECT 8 CompanyID, 115 BillAmount FROM dual
    ),

    --Dummy tables above
    --My current way of doing it below
    companies AS
    (SELECT c.*,
    cs.sector
    FROM company c
    LEFT OUTER JOIN CompanySector cs
    ON c.companyID = cs.companyID
    ),
    sectors AS
    (SELECT levelOne.companyID,
    NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) sector
    FROM companies levelOne
    LEFT OUTER JOIN companies levelTwo
    ON levelOne.parentcompanyid = levelTwo.companyID
    LEFT OUTER JOIN companies levelThree
    ON levelTwo.parentcompanyid = levelThree.companyID
    WHERE NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) IS NOT NULL
    )
    SELECT s.sector,
    SUM(t.billamount)
    FROM sectors s
    INNER JOIN timesheets t
    ON s.companyID = t.companyID
    GROUP BY sector;


    What is a cleaner and more efficient way of doing this?










    share|improve this question


























      2












      2








      2


      1






      I have a hierarchical company structure where each company has an optional company sector. Child companies inherit their parent's sector if they don't have their own, but the child company sector overrides its parent's if the child one.



      I need to produce a sum of the bill amount grouped by sector. Companies with no sector are ignored.



      The ParentCompanyID column in the Company table is a foreign key to itself. There can be an unlimited number of parent/child levels.



      Company Table



      CompanyID ParentCompanyID
      1 null
      2 1
      3 2
      4 null
      5 4
      6 null
      7 6
      8 7


      CompanySector Table



      CompanyID Sector
      1 Distribution
      4 Distribution
      5 Manufacturing
      8 Manufacturing


      Timesheet Table



      CompanyID BillAmount
      1 100
      1 200
      2 100
      3 50
      4 25
      5 75
      6 75
      7 115
      8 115


      The result I expect to see here is:



       Sector BillAmount 
      Distribution 475
      Manufacturing 190


      Below is how I am currently doing it. It is extremely inefficient and doesn't work for unlimited number of hierarchical levels.



      WITH Company AS
      ( SELECT 1 CompanyID, NULL ParentCompanyID FROM dual
      UNION
      SELECT 2, 1 FROM dual
      UNION
      SELECT 3, 2 FROM dual
      UNION
      SELECT 4, NULL FROM dual
      UNION
      SELECT 5, 4 FROM dual
      UNION
      SELECT 6, NULL FROM dual
      UNION
      SELECT 7, 6 FROM dual
      UNION
      SELECT 8, 7 FROM dual
      ),
      CompanySector AS
      ( SELECT 1 CompanyID, 'Distribution' Sector FROM dual
      UNION
      SELECT 4 , 'Distribution' FROM dual
      UNION
      SELECT 5 , 'Manufacturing' FROM dual
      UNION
      SELECT 8 , 'Manufacturing' FROM dual
      ),
      Timesheets AS
      ( SELECT 1 CompanyID, 100 BillAmount FROM dual
      UNION
      SELECT 1 CompanyID, 200 BillAmount FROM dual
      UNION
      SELECT 2 CompanyID, 100 BillAmount FROM dual
      UNION
      SELECT 3 CompanyID, 50 BillAmount FROM dual
      UNION
      SELECT 4 CompanyID, 25 BillAmount FROM dual
      UNION
      SELECT 5 CompanyID, 75 BillAmount FROM dual
      UNION
      SELECT 6 CompanyID, 75 BillAmount FROM dual
      UNION
      SELECT 7 CompanyID, 115 BillAmount FROM dual
      UNION
      SELECT 8 CompanyID, 115 BillAmount FROM dual
      ),

      --Dummy tables above
      --My current way of doing it below
      companies AS
      (SELECT c.*,
      cs.sector
      FROM company c
      LEFT OUTER JOIN CompanySector cs
      ON c.companyID = cs.companyID
      ),
      sectors AS
      (SELECT levelOne.companyID,
      NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) sector
      FROM companies levelOne
      LEFT OUTER JOIN companies levelTwo
      ON levelOne.parentcompanyid = levelTwo.companyID
      LEFT OUTER JOIN companies levelThree
      ON levelTwo.parentcompanyid = levelThree.companyID
      WHERE NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) IS NOT NULL
      )
      SELECT s.sector,
      SUM(t.billamount)
      FROM sectors s
      INNER JOIN timesheets t
      ON s.companyID = t.companyID
      GROUP BY sector;


      What is a cleaner and more efficient way of doing this?










      share|improve this question














      I have a hierarchical company structure where each company has an optional company sector. Child companies inherit their parent's sector if they don't have their own, but the child company sector overrides its parent's if the child one.



      I need to produce a sum of the bill amount grouped by sector. Companies with no sector are ignored.



      The ParentCompanyID column in the Company table is a foreign key to itself. There can be an unlimited number of parent/child levels.



      Company Table



      CompanyID ParentCompanyID
      1 null
      2 1
      3 2
      4 null
      5 4
      6 null
      7 6
      8 7


      CompanySector Table



      CompanyID Sector
      1 Distribution
      4 Distribution
      5 Manufacturing
      8 Manufacturing


      Timesheet Table



      CompanyID BillAmount
      1 100
      1 200
      2 100
      3 50
      4 25
      5 75
      6 75
      7 115
      8 115


      The result I expect to see here is:



       Sector BillAmount 
      Distribution 475
      Manufacturing 190


      Below is how I am currently doing it. It is extremely inefficient and doesn't work for unlimited number of hierarchical levels.



      WITH Company AS
      ( SELECT 1 CompanyID, NULL ParentCompanyID FROM dual
      UNION
      SELECT 2, 1 FROM dual
      UNION
      SELECT 3, 2 FROM dual
      UNION
      SELECT 4, NULL FROM dual
      UNION
      SELECT 5, 4 FROM dual
      UNION
      SELECT 6, NULL FROM dual
      UNION
      SELECT 7, 6 FROM dual
      UNION
      SELECT 8, 7 FROM dual
      ),
      CompanySector AS
      ( SELECT 1 CompanyID, 'Distribution' Sector FROM dual
      UNION
      SELECT 4 , 'Distribution' FROM dual
      UNION
      SELECT 5 , 'Manufacturing' FROM dual
      UNION
      SELECT 8 , 'Manufacturing' FROM dual
      ),
      Timesheets AS
      ( SELECT 1 CompanyID, 100 BillAmount FROM dual
      UNION
      SELECT 1 CompanyID, 200 BillAmount FROM dual
      UNION
      SELECT 2 CompanyID, 100 BillAmount FROM dual
      UNION
      SELECT 3 CompanyID, 50 BillAmount FROM dual
      UNION
      SELECT 4 CompanyID, 25 BillAmount FROM dual
      UNION
      SELECT 5 CompanyID, 75 BillAmount FROM dual
      UNION
      SELECT 6 CompanyID, 75 BillAmount FROM dual
      UNION
      SELECT 7 CompanyID, 115 BillAmount FROM dual
      UNION
      SELECT 8 CompanyID, 115 BillAmount FROM dual
      ),

      --Dummy tables above
      --My current way of doing it below
      companies AS
      (SELECT c.*,
      cs.sector
      FROM company c
      LEFT OUTER JOIN CompanySector cs
      ON c.companyID = cs.companyID
      ),
      sectors AS
      (SELECT levelOne.companyID,
      NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) sector
      FROM companies levelOne
      LEFT OUTER JOIN companies levelTwo
      ON levelOne.parentcompanyid = levelTwo.companyID
      LEFT OUTER JOIN companies levelThree
      ON levelTwo.parentcompanyid = levelThree.companyID
      WHERE NVL(levelOne.sector, NVL(levelTwo.sector, NVL(levelThree.sector, NULL))) IS NOT NULL
      )
      SELECT s.sector,
      SUM(t.billamount)
      FROM sectors s
      INNER JOIN timesheets t
      ON s.companyID = t.companyID
      GROUP BY sector;


      What is a cleaner and more efficient way of doing this?







      sql oracle hierarchical-data






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 28 at 17:35









      Alex03Alex03

      561 silver badge7 bronze badges




      561 silver badge7 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          1
















          I believe this will do it. Using the hierarchical query syntax, populate sector from the parent record where needed.



          WITH
          base_sectors AS (
          SELECT * FROM company LEFT OUTER JOIN companySector USING (companyID)
          )
          , final_sectors AS (
          SELECT companyID, NVL( sector, PRIOR sector ) AS sector
          FROM base_sectors
          START WITH parentCompanyID IS NULL
          CONNECT BY parentCompanyID = PRIOR companyID
          )
          SELECT s.sector,
          SUM(t.billamount)
          FROM final_sectors s
          INNER JOIN timesheets t
          ON s.companyID = t.companyID
          GROUP BY sector;





          share|improve this answer



























          • Thanks for the quick reply, this is very close but I think a piece is missing here. It's only including companies that have an exact link to a companysector. For instance, companies 2 and 3 are not inheriting the sector from company 1, their parent company.

            – Alex03
            Mar 28 at 18:12











          • Ugh, sorry, that first join should be an outer join. Updated!

            – Dave Costa
            Mar 28 at 18:37











          • No apology needed! This is sooooo close. I don't think I explained correctly that children should inherit sectors all the way up until it finds a non null value, not just from their direct parent. So company 3 should pull the sector from two levels up (company 1). In your query company 3 has a null sector. I'm fiddling with it and can't quite get it.

            – Alex03
            Mar 28 at 18:49












          • Try replacing the NVL expression with SYS_CONNECT_BY_PATH(sector,'/'). That should give you a string with the sector values from all ancestor records. Then hopefully you can parse out the last non-NULL value.

            – Dave Costa
            Mar 28 at 20:09











          • I went with REGEXP_SUBSTR(trim(trailing '.' FROM SYS_CONNECT_BY_PATH(sector,'.')), '[^.]+$') AS sector This is exactly what I was looking for. The efficiency is up for debate, but it's cleaner than what I had. Thanks!

            – Alex03
            Mar 28 at 20:50














          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );














          draft saved

          draft discarded
















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55403757%2fhierarchical-query-child-override%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1
















          I believe this will do it. Using the hierarchical query syntax, populate sector from the parent record where needed.



          WITH
          base_sectors AS (
          SELECT * FROM company LEFT OUTER JOIN companySector USING (companyID)
          )
          , final_sectors AS (
          SELECT companyID, NVL( sector, PRIOR sector ) AS sector
          FROM base_sectors
          START WITH parentCompanyID IS NULL
          CONNECT BY parentCompanyID = PRIOR companyID
          )
          SELECT s.sector,
          SUM(t.billamount)
          FROM final_sectors s
          INNER JOIN timesheets t
          ON s.companyID = t.companyID
          GROUP BY sector;





          share|improve this answer



























          • Thanks for the quick reply, this is very close but I think a piece is missing here. It's only including companies that have an exact link to a companysector. For instance, companies 2 and 3 are not inheriting the sector from company 1, their parent company.

            – Alex03
            Mar 28 at 18:12











          • Ugh, sorry, that first join should be an outer join. Updated!

            – Dave Costa
            Mar 28 at 18:37











          • No apology needed! This is sooooo close. I don't think I explained correctly that children should inherit sectors all the way up until it finds a non null value, not just from their direct parent. So company 3 should pull the sector from two levels up (company 1). In your query company 3 has a null sector. I'm fiddling with it and can't quite get it.

            – Alex03
            Mar 28 at 18:49












          • Try replacing the NVL expression with SYS_CONNECT_BY_PATH(sector,'/'). That should give you a string with the sector values from all ancestor records. Then hopefully you can parse out the last non-NULL value.

            – Dave Costa
            Mar 28 at 20:09











          • I went with REGEXP_SUBSTR(trim(trailing '.' FROM SYS_CONNECT_BY_PATH(sector,'.')), '[^.]+$') AS sector This is exactly what I was looking for. The efficiency is up for debate, but it's cleaner than what I had. Thanks!

            – Alex03
            Mar 28 at 20:50
















          1
















          I believe this will do it. Using the hierarchical query syntax, populate sector from the parent record where needed.



          WITH
          base_sectors AS (
          SELECT * FROM company LEFT OUTER JOIN companySector USING (companyID)
          )
          , final_sectors AS (
          SELECT companyID, NVL( sector, PRIOR sector ) AS sector
          FROM base_sectors
          START WITH parentCompanyID IS NULL
          CONNECT BY parentCompanyID = PRIOR companyID
          )
          SELECT s.sector,
          SUM(t.billamount)
          FROM final_sectors s
          INNER JOIN timesheets t
          ON s.companyID = t.companyID
          GROUP BY sector;





          share|improve this answer



























          • Thanks for the quick reply, this is very close but I think a piece is missing here. It's only including companies that have an exact link to a companysector. For instance, companies 2 and 3 are not inheriting the sector from company 1, their parent company.

            – Alex03
            Mar 28 at 18:12











          • Ugh, sorry, that first join should be an outer join. Updated!

            – Dave Costa
            Mar 28 at 18:37











          • No apology needed! This is sooooo close. I don't think I explained correctly that children should inherit sectors all the way up until it finds a non null value, not just from their direct parent. So company 3 should pull the sector from two levels up (company 1). In your query company 3 has a null sector. I'm fiddling with it and can't quite get it.

            – Alex03
            Mar 28 at 18:49












          • Try replacing the NVL expression with SYS_CONNECT_BY_PATH(sector,'/'). That should give you a string with the sector values from all ancestor records. Then hopefully you can parse out the last non-NULL value.

            – Dave Costa
            Mar 28 at 20:09











          • I went with REGEXP_SUBSTR(trim(trailing '.' FROM SYS_CONNECT_BY_PATH(sector,'.')), '[^.]+$') AS sector This is exactly what I was looking for. The efficiency is up for debate, but it's cleaner than what I had. Thanks!

            – Alex03
            Mar 28 at 20:50














          1














          1










          1









          I believe this will do it. Using the hierarchical query syntax, populate sector from the parent record where needed.



          WITH
          base_sectors AS (
          SELECT * FROM company LEFT OUTER JOIN companySector USING (companyID)
          )
          , final_sectors AS (
          SELECT companyID, NVL( sector, PRIOR sector ) AS sector
          FROM base_sectors
          START WITH parentCompanyID IS NULL
          CONNECT BY parentCompanyID = PRIOR companyID
          )
          SELECT s.sector,
          SUM(t.billamount)
          FROM final_sectors s
          INNER JOIN timesheets t
          ON s.companyID = t.companyID
          GROUP BY sector;





          share|improve this answer















          I believe this will do it. Using the hierarchical query syntax, populate sector from the parent record where needed.



          WITH
          base_sectors AS (
          SELECT * FROM company LEFT OUTER JOIN companySector USING (companyID)
          )
          , final_sectors AS (
          SELECT companyID, NVL( sector, PRIOR sector ) AS sector
          FROM base_sectors
          START WITH parentCompanyID IS NULL
          CONNECT BY parentCompanyID = PRIOR companyID
          )
          SELECT s.sector,
          SUM(t.billamount)
          FROM final_sectors s
          INNER JOIN timesheets t
          ON s.companyID = t.companyID
          GROUP BY sector;






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 28 at 18:36

























          answered Mar 28 at 17:52









          Dave CostaDave Costa

          40.2k6 gold badges50 silver badges67 bronze badges




          40.2k6 gold badges50 silver badges67 bronze badges















          • Thanks for the quick reply, this is very close but I think a piece is missing here. It's only including companies that have an exact link to a companysector. For instance, companies 2 and 3 are not inheriting the sector from company 1, their parent company.

            – Alex03
            Mar 28 at 18:12











          • Ugh, sorry, that first join should be an outer join. Updated!

            – Dave Costa
            Mar 28 at 18:37











          • No apology needed! This is sooooo close. I don't think I explained correctly that children should inherit sectors all the way up until it finds a non null value, not just from their direct parent. So company 3 should pull the sector from two levels up (company 1). In your query company 3 has a null sector. I'm fiddling with it and can't quite get it.

            – Alex03
            Mar 28 at 18:49












          • Try replacing the NVL expression with SYS_CONNECT_BY_PATH(sector,'/'). That should give you a string with the sector values from all ancestor records. Then hopefully you can parse out the last non-NULL value.

            – Dave Costa
            Mar 28 at 20:09











          • I went with REGEXP_SUBSTR(trim(trailing '.' FROM SYS_CONNECT_BY_PATH(sector,'.')), '[^.]+$') AS sector This is exactly what I was looking for. The efficiency is up for debate, but it's cleaner than what I had. Thanks!

            – Alex03
            Mar 28 at 20:50


















          • Thanks for the quick reply, this is very close but I think a piece is missing here. It's only including companies that have an exact link to a companysector. For instance, companies 2 and 3 are not inheriting the sector from company 1, their parent company.

            – Alex03
            Mar 28 at 18:12











          • Ugh, sorry, that first join should be an outer join. Updated!

            – Dave Costa
            Mar 28 at 18:37











          • No apology needed! This is sooooo close. I don't think I explained correctly that children should inherit sectors all the way up until it finds a non null value, not just from their direct parent. So company 3 should pull the sector from two levels up (company 1). In your query company 3 has a null sector. I'm fiddling with it and can't quite get it.

            – Alex03
            Mar 28 at 18:49












          • Try replacing the NVL expression with SYS_CONNECT_BY_PATH(sector,'/'). That should give you a string with the sector values from all ancestor records. Then hopefully you can parse out the last non-NULL value.

            – Dave Costa
            Mar 28 at 20:09











          • I went with REGEXP_SUBSTR(trim(trailing '.' FROM SYS_CONNECT_BY_PATH(sector,'.')), '[^.]+$') AS sector This is exactly what I was looking for. The efficiency is up for debate, but it's cleaner than what I had. Thanks!

            – Alex03
            Mar 28 at 20:50

















          Thanks for the quick reply, this is very close but I think a piece is missing here. It's only including companies that have an exact link to a companysector. For instance, companies 2 and 3 are not inheriting the sector from company 1, their parent company.

          – Alex03
          Mar 28 at 18:12





          Thanks for the quick reply, this is very close but I think a piece is missing here. It's only including companies that have an exact link to a companysector. For instance, companies 2 and 3 are not inheriting the sector from company 1, their parent company.

          – Alex03
          Mar 28 at 18:12













          Ugh, sorry, that first join should be an outer join. Updated!

          – Dave Costa
          Mar 28 at 18:37





          Ugh, sorry, that first join should be an outer join. Updated!

          – Dave Costa
          Mar 28 at 18:37













          No apology needed! This is sooooo close. I don't think I explained correctly that children should inherit sectors all the way up until it finds a non null value, not just from their direct parent. So company 3 should pull the sector from two levels up (company 1). In your query company 3 has a null sector. I'm fiddling with it and can't quite get it.

          – Alex03
          Mar 28 at 18:49






          No apology needed! This is sooooo close. I don't think I explained correctly that children should inherit sectors all the way up until it finds a non null value, not just from their direct parent. So company 3 should pull the sector from two levels up (company 1). In your query company 3 has a null sector. I'm fiddling with it and can't quite get it.

          – Alex03
          Mar 28 at 18:49














          Try replacing the NVL expression with SYS_CONNECT_BY_PATH(sector,'/'). That should give you a string with the sector values from all ancestor records. Then hopefully you can parse out the last non-NULL value.

          – Dave Costa
          Mar 28 at 20:09





          Try replacing the NVL expression with SYS_CONNECT_BY_PATH(sector,'/'). That should give you a string with the sector values from all ancestor records. Then hopefully you can parse out the last non-NULL value.

          – Dave Costa
          Mar 28 at 20:09













          I went with REGEXP_SUBSTR(trim(trailing '.' FROM SYS_CONNECT_BY_PATH(sector,'.')), '[^.]+$') AS sector This is exactly what I was looking for. The efficiency is up for debate, but it's cleaner than what I had. Thanks!

          – Alex03
          Mar 28 at 20:50






          I went with REGEXP_SUBSTR(trim(trailing '.' FROM SYS_CONNECT_BY_PATH(sector,'.')), '[^.]+$') AS sector This is exactly what I was looking for. The efficiency is up for debate, but it's cleaner than what I had. Thanks!

          – Alex03
          Mar 28 at 20:50





















          draft saved

          draft discarded















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55403757%2fhierarchical-query-child-override%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현