Self-regulation table with child table

I have a table for self-regulation with content like this:

Self-referencing parent table
ID  ParentID    Name
---------------------
1               John
2   1           Mike
3   2           Erin
4   1           Janie
5               Eric
6   5           Peter

The tree hierarchy should look like this:

  • John
    • Mike
      • Erin
    • Jeni
  • Eric
    • Peter

And the child table in which the sheet of the parent table is stored is as follows:

ID  Sales
3   100
3   100
4   200
4   200
6   300
6   300
6   300

I am trying to collapse the sum from a node sheet to a hierarchy so that it returns as ..

ID  Name    Sum
1   John    800
2   Mike    200
3   Erin    200
4   Janie   400
5   Eric    900
6   Peter   900

Any ideas how to achieve this in sql 2008? Thanks in advance.

+5
source share
2 answers

EDIT All units exited CTE

WITH
  tree AS
(
  SELECT
    id                AS root_id,
    name              AS root_name,
    id                AS leaf_id
  FROM
    yourTreeTable

  UNION ALL

  SELECT
    tree.root_id      AS root_id,
    tree.name         AS root_name,
    yourTreeTable.id  AS leaf_id
  FROM
    tree
  INNER JOIN
    yourTreeTable
      ON tree.leaf_id = yourTreeTable.ParentID
)
SELECT
  tree.root_id,
  tree.root_name,
  COALESCE(SUM(yourScoresTable.score), 0) AS total
FROM
  tree
LEFT JOIN
  yourScoresTable
    ON yourScoresTable.ID = tree.leafID
GROUP BY
  tree.root_id,
  tree.root_name
+5
source

There he is:

Let's admit this scheme:

create table #parent (
ID int,
ParentID int,
Name varchar(50) );

create table #child (
ID int,
Sales int );

The request is explained independently:

WITH 
  tree AS
(
  SELECT
    id as id_parent,
    id as id
  FROM
    #parent
  UNION ALL
  SELECT
    tree.id_parent as id_parent,
    #parent.id AS id
  FROM
    tree
  INNER JOIN
    #parent    
      ON tree.id = #parent.ParentID
)
SELECT
  #parent.id,
  #parent.name,
  COALESCE(SUM(#child.Sales), 0) AS total
FROM
  #parent
LEFT JOIN
  tree
    ON #parent.ID = tree.id_parent
LEFT JOIN
  #child on tree.id = #child.id
GROUP BY
  #parent.id,
  #parent.name

CTE "" (#parent), "". .

EDITED

.

+1

All Articles