我使用的是SQL Server2005,我有一个名为Docs的表,其中有一个名为Path的列。
Path列包含文件路径:
"C:\MyDocs\1.txt"
"C:\MyDocs\Folder1\3.txt"我需要我的查询在一个查询中检索每个文件夹和子文件夹有多少子文件夹。
在上面的示例中,我需要查询来检索:
"MyDocs“的3个子文件夹(1个文件夹和2个文件) "Folder1”的1个子文件夹(1个文件)。
有什么想法吗?
谢谢。
发布于 2011-05-15 22:47:15
您可以使用字符串操作来解决这个问题,为了清楚起见,还可以使用两个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:\some\folder\%' -- all folders below C:\some\folder
go未测试!
发布于 2011-05-15 22:02:26
添加具有目录路径的列目录(例如对于"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我没有运行查询,但思路应该是清晰的。
发布于 2011-05-15 21:50:57
您需要将路径拆分为单独的字符串,并对数据进行规范化。这是一个关于在sql中拆分字符串的previous question。
完成此操作后,您可以使用Recursive CTE获取数据。
https://stackoverflow.com/questions/6008757
复制相似问题