SQL Server 2005 - 分层 SQL 查询



我正在使用SQL Server 2005,我有一个叫做Docs的表,其中有一个名为Path的列。

Path列包含文件路径:

"C:MyDocs1.txt"
"C:MyDocsFolder13.txt"

我需要我的查询在单个查询中检索每个文件夹和子文件夹有多少个子文件夹。

在上面的示例中,我需要查询来检索:

3 个子项(1 个文件夹和 2 个文件)用于"MyDocs"文件夹 1"的 1 个子项(1 个文件)。

有什么想法吗?

谢谢。

添加一个带有目录路径的列dir(例如,对于"C:\MyDocs\Folder1\3.txt",它应该包含"C:\MyDocs\Folder1\")。然后:

select dirs.path, count(*) from Docs files 
join (select distinct dir as path from Docs) dirs
    on (files.dir like dirs.path + '%')
group by dirs.path

我没有运行查询,但想法应该很清楚。

您需要将路径拆分为单独的字符串并规范化数据。这是之前关于在 sql 中拆分字符串的问题。

完成此操作后,您可以使用递归 CTE 来获取数据。

您可以使用字符串操作来解决此问题,为清楚起见,可以使用两个 CTE:

WITH
R1(RevPath) as (select reverse(Path) from Docs),
R2(ParentFolder) as
(select reverse( substring(RevPath, charindex('', RevPath), 3333)) from R1)
select ParentFolder, count(*) from R2
group by ParentFolder
go

您可能需要根据您的数据对此进行一些调整。如果表仅列出文件,则此查询应该没问题。如果它还列出了带有尾随反斜杠的文件夹,请从计数中减去 1。

如何获取其中包含的所有文件夹和文件的列表

WITH
R1(Path, RevPath) as (select Path, reverse(Path) from Docs),
R2(ParentFolder, Path) as
(select
  reverse( substring(RevPath, charindex('', RevPath), 3333)),
  Path
 from R1)
select * from R2
where ParentFolder LIKE 'C:somefolder%' -- all folders below C:somefolder
go

未测试!

最新更新