我有以下问题:我有一个用于维护分层数据的表。我想在SQL 2005中使用CTE。
WITH tree (id, parentid, code, name) AS
(
SELECT id, ofs.ParentID, ofs.code, ofs.name
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, ofs.code, ofs.name
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree
但是我想按代码排序,结果如下:
1
1/1
1/1/1
1/1/2
1/2/1
1/2/2
2
4/1
等。有任何想法吗?
答案 0 :(得分:4)
要获取连接值,您需要在with。中执行此操作。
要进行排序,您需要在最后一次选择中添加一个订单。
WITH tree (id, parentid, code, name) AS
(
SELECT id, ofs.ParentID, ofs.code, ofs.name
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, tree.code+'/'+ofs.code, ofs.name
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree order by code
此外,如果代码不是varchar,则必须转换此代码(tree.code+'/'+ofs.code
)中的代码列才能生效。
答案 1 :(得分:2)
Loki,我有类似的查询,但它并没有像我想要的那样排序,而是通过代码 - 它是星期五,我超载了。
无论如何,运行你的查询给了我一个错误,有必要施放;我必须按照以下方式改变它:
WITH tree (id, parentid, name, code) AS
(
SELECT id, ofs.ParentID, ofs.name, CAST(ofs.name as varchar(255))
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, ofs.name, CAST(tree.code+'/'+ofs.name as varchar(255))
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree order by code
问题在于,尽管名称是varchar,但仍需要转换为varchar。对于大树,varchar(255)很可能是不够的。
所以我做了一个版本,上面提到的问题不是那么大:
WITH tree (id, parentid, name, code) AS
(
SELECT id, ofs.ParentID, ofs.name,
CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255))
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, ofs.name,
CAST(tree.code +'/' + CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255)) as varchar(255))
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree order by code
但是我不喜欢这种解决方案需要施放。有没有更好的解决方案?