【发布时间】:2015-04-25 04:12:21
【问题描述】:
我发现了一篇非常有用的文章,位于: Simplest way to do a recursive self-join in SQL Server?
假设在此示例中,有另一个名为“Quantity”的列存储如下所示的整数:
PersonID | Initials | ParentID | Quantity
1 CJ NULL 1
2 EB 1 2
3 MB 1 1
4 SW 2 1
5 YT NULL 1
6 IS 5 1
如果我要求 CJ 的等级制度,那就是
PersonID | Initials | ParentID | Quantity | HasSubordinate
1 CJ NULL 2 1
2 EB 1 1 1
3 MB 1 1 1
4 SW 2 1 0
HasSubordinate 列指定层次结构中的最后一个个体。我想显示层次结构中的最后一个人,前一行的数量相乘。在这种情况下,数量为 2 (2 x 1 x 1 x 1 = 2)。
PersonID | Initials | ParentID | Quantity | HasSubordinate
4 SW 2 2 0
我的代码:
WITH q AS
(
SELECT *
FROM mytable
WHERE PersonID = 1
UNION ALL
SELECT m.*
FROM mytable m
JOIN q
ON m.parentID = q.PersonID
)
SELECT *
FROM q
WHERE HasSubordinate = 0
非常感谢任何帮助!
【问题讨论】: