1

我在 SQL Server 2005 中有一个层次结构表,其中包含员工-> 经理-> 部门-> 位置-> 状态。

层次表的示例表:

ID   Name           ParentID   Type
1    PA             NULL       0 (group)
2    Pittsburgh     1          1 (subgroup)
3    Accounts       2          1 
4    Alex           3          2 (employee)
5    Robin          3          2
6    HR             2          1
7    Robert         6          2

第二个是包含员工工资详细信息 ID 和 Salary 的事实表。

事实表的样本数据:

ID    Salary
4     6000
5     5000
7     4000

有没有什么好的方法可以从层次结构表中显示层次结构,并根据员工的工资总和。预期的结果就像

Name              Salary
PA                15000   (Pittsburgh + others(if any)) 
  Pittusburgh     15000   (Accounts + HR)
    Accounts      11000   (Alex + Robin)
      Alex         6000   (direct values)
      Robin        5000
    HR             4000
      Robert       4000

在我的生产环境中,层次表可能包含 23000+ 行,事实表可能包含 300,000+ 行。因此,我想为查询提供任何级别的 groupid 以仅检索其子项及其相应的聚合值。有更好的解决方案吗?

4

1 回答 1

1

此解决方案产生正确的结果。只要索引到位,这应该对您的生产数据集执行良好,但我没有在您的示例数据上对其进行测试。

DECLARE @tree TABLE
(ID INT
,name VARCHAR(15)
,ParentID INT
,TYPE TINYINT
)

DECLARE @salary TABLE
(ID INT
,Salary INT
)

INSERT @tree
      SELECT 1,'PA',NULL,0
UNION SELECT 2,'Pittsburgh',1,1
UNION SELECT 3,'Accounts',2,1
UNION SELECT 4,'Alex',3,2
UNION SELECT 5,'Robin',3,2
UNION SELECT 6,'HR',2,1
UNION SELECT 7,'Robert',6,2


INSERT @salary
      SELECT 4,6000
UNION SELECT 5,5000
UNION SELECT 7,4000


;WITH salaryCTE
AS
(
        SELECT t.*
               ,s.Salary
        FROM      @tree         AS t
        LEFT JOIN @salary       AS s
        ON        s.ID = t.ID
)
,recCTE
AS
(
        SELECT t.ID
               ,CAST(t.name AS VARCHAR(MAX)) AS name
               ,t.ParentID 
               ,ISNULL(t.Salary,0) AS Salary
               ,0 AS LEVEL
               ,CAST(t.ID AS VARCHAR(100)) AS ord
        FROM  salaryCTE   AS t
        WHERE t.ParentID IS NULL

        UNION ALL

        SELECT t.ID
               ,CAST(REPLICATE(' ',r.LEVEL) + t.name AS VARCHAR(MAX)) AS name
               ,t.ParentID
               ,ISNULL(t.Salary,0) AS Salary
               ,r.LEVEL + 1
               ,CAST(r.ord + '|' + CAST(t.ID AS VARCHAR(11)) AS VARCHAR(100)) AS ord
        FROM      salaryCTE     AS t        
        JOIN      recCTE        AS r
        ON        r.ID = t.ParentID
)
SELECT name
       ,salary
FROM (       
        SELECT r1.name
               ,r1.ord
               ,SUM(r2.salary) AS salary

        FROM recCTE AS r1
        LEFT JOIN recCTE AS r2
        ON   r2.ord LIKE r1.ord + '%'
        GROUP BY r1.name,r1.ord 
     ) AS x
ORDER BY ord,name
于 2010-03-12T09:37:00.073 回答