-1
    GoupName    Id   UnderGRoupId Quantity
    Computer    66    57          0
    Keyboard    67    66          0
    Monitor     68    66          0
    Mouse       69    66          25
    CPU         70    66          0
    Stationary  71    57          0
    Pencil      72    71          0
    Ruler       73    71          0
    Mechanical  74    67          30
    Membrane    75    67          0

这是我的视图,其中显示了直接属于这些组的项目数量。我希望它递归地添加直接或间接属于主要组的组数量,例如计算机。

        GoupName    Id   UnderGRoupId Quantity
        Computer    66    57          55
        Keyboard    67    66          30
        Monitor     68    66          0
        Mouse       69    66          25
        CPU         70    66          0
        Stationary  71    57          0
        Pencil      72    71          0
        Ruler       73    71          0
        Mechanical  74    67          30
        Membrane    75    67          0

这就是我希望我的函数返回值的方式。

4

1 回答 1

1

在 SQL Server 中,查询将如下所示:

WITH temp (ID, UnderGRoupId, Quantity)
AS
(
    SELECT ID, UnderGRoupId, Quantity
    FROM MyTable
    WHERE NOT EXISTS (SELECT * FROM MyTable cc WHERE cc.UnderGRoupId = MyTable.ID)

    UNION ALL

    SELECT MyTable.ID, MyTable.UnderGRoupId, Quantity + MyTable.Quantity
    FROM MyTable
    INNER JOIN temp ON MyTable.ID = temp.UnderGRoupId
)

SELECT ID, SUM(Quantity) FROM
(SELECT ID, Quantity - (SELECT Amount FROM MyTable M WHERE M.ID = temp.ID) Quantity
FROM temp) X
GROUP BY ID
于 2013-09-28T06:44:00.120 回答