分层ToDoList作为邻接列表

时间:2016-07-11 06:15:07

标签: sql sql-server sql-server-2008

我正在构建一个带有层次结构的待办事项列表,我正在为它寻找一个好的逻辑,并发现它与邻接列表有关。

目标是能够使用分层任务执行待办事项列表(一个任务是根,然后可以有节点,节点可以有自己的节点等等。) 所以我建了一张桌子

CREATE TABLE [dbo].[Tasks](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Owner] [nvarchar](max) NOT NULL,
[Parent] [int] NULL,

插入数据后,表格如下所示:

enter image description here

我想要一个向我显示所有根的查询,如果某个根有节点,那么也要显示它

我的查询是

SELECT t.*, COUNT(tr.Parent) as SubCount
FROM Tasks t
INNER JOIN Tasks tr on t.Id = tr.Parent
GROUP BY t.Name, t.Owner, t.Id, t.Parent
UNION
SELECT t.*, 0 as SubCount
FROM Tasks t
where Parent IS NULL;

但结果是:

enter image description here

预期结果应仅显示具有父IS NULL的行和具有子节点的行,例如:

enter image description here

这里的查询应该是什么?

2 个答案:

答案 0 :(得分:1)

试试这个,

SELECT
    T.Id,
    T.Name,
    T.Owner,
    T.Parent,
    (SELECT COUNT(IT.Id) FROM Tasks IT WHERE IT.Parent = T.Id) AS SubCount
FROM
    Tasks T
WHERE
    T.Parent IS NULL

答案 1 :(得分:0)

试试这个。,

select id, name , owner, parent,sum(SubCount) SubCount
from(
SELECT t.*, COUNT(tr.Parent) as SubCount
FROM Tasks t
INNER JOIN Tasks tr on t.Id = tr.Parent
GROUP BY t.Name, t.Owner, t.Id, t.Parent
UNION
SELECT t.*, 0 as SubCount
FROM Tasks t
where Parent IS NULL;
)d
group by id, name , owner, parent