自我引用表与子表

时间:2012-01-03 22:59:49

标签: sql sql-server-2008 tsql hierarchical-data

我有一个自我引用表,内容如下:

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

树层次结构应该如下所示

  • 约翰
    • 麦克
      • 埃林
    • 珍妮
  • 埃里克
    • 彼得

一个子表,用于存储父表的叶子,如下所示:

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

我正在尝试将叶子节点的总和汇总到层次结构,以便它返回...

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

如何在sql 2008中实现这一点?提前谢谢。

2 个答案:

答案 0 :(得分:5)

编辑所有汇总都移出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

答案 1 :(得分:1)

这是:

让我们来讨论这个架构:

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

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

查询是自我解释的:

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)的“叶子”列表,然后查询总结此“叶子”的所有销售额。 You can test it running

<强> EDITED

查询已修复。