0

我有一个包含如下文件夹列表的表:

Path                    Size
C:\ParentFolder\A       123
C:\ParentFolder\A\B     442434
C:\ParentFolder\A\B\C   13413412
C:\ParentFolder\D       2422341234
C:\ParentFolder\D\E     3342
C:\ParentFolder\D\E\F   2
C:\ParentFolder\D\E\G   2
...

我正在寻找 SUM、GROUP BY 和 PATINDEX/LTRIM/SUBSTRING/等的某种组合。这会给我这个:

Path                    SumSize
C:\ParentFolder\A       13855969
C:\ParentFolder\D       2422344580
...

C:\ParentFolder 是已知前缀,但 A、D 等。是可变文件夹名称。我是否需要编写一个函数来完成它,或者我可以使用字符串函数的某种组合?

4

5 回答 5

1
select r.Path, sum(Size) as SumSize
from MyTable m
inner join (
    select Path
    from MyTable 
    where charindex('\', Path, len('C:\ParentFolder\') + 1) = 0 
) r on charindex(r.Path, m.Path, 0) = 1
group by r.Path

SQL Fiddle 示例在这里

于 2012-06-07T14:13:06.043 回答
0

从您的测试集开始,

CREATE TABLE #MyTable (Folder varchar(100) not null, Size bigint not null)

INSERT #MyTable values
  ('C:\ParentFolder\A'     ,  123)
 ,('C:\ParentFolder\A\B'   ,  442434)
 ,('C:\ParentFolder\A\B\C' ,  13413412)
 ,('C:\ParentFolder\D'     ,  2422341234)
 ,('C:\ParentFolder\D\E'   ,  3342)
 ,('C:\ParentFolder\D\E\F' ,  2)
 ,('C:\ParentFolder\D\E\G' ,  2)

您首先要确定要汇总的文件夹。我在这里通过将它们加载到临时表中来做到这一点:

DECLARE @Targets table (Folder varchar(100) not null)
INSERT @Targets values
  ('C:\ParentFolder\A')
 ,('C:\ParentFolder\D')

从这里很容易,使用 like 子句:

SELECT ta.Folder, sum(Size) TotalSize
 from @Targets ta
  left outer join #MyTable mt
   on mt.Folder like ta.Folder + '%'
 group by ta.Folder

如果您的文件夹包含like子句使用的保留字符:% _ ] [和其他一些字符,则可能会出现复杂情况。

于 2012-06-07T14:15:29.380 回答
0

假设总是有一个最高级别目录的条目(即如果有一个c:\xxx\yyy\zzz总是会有一个c:\xxx\yyy怎么样

;with roots (root) as (
     select distinct
        path + '\' 
     from 
        thetable
     where 
        --only include paths with 2 x \
        len(path) - 2 = len(replace(path, '\', '')) 
)
select
    roots.root,
    sum(thetable.size)
from 
    roots
inner join 
    thetable on left(thetable.path + '\', len(roots.root)) = roots.root 
group by
    roots.root
于 2012-06-07T14:40:06.263 回答
0
 select path, (select sum(Size) 
               from Paths p2 where p2.Path like p1.Path+'%') as total
 from Paths p1
 where charIndex('\',Path, len('C:\ParentFolder\')+1) = 0
于 2012-06-07T14:41:56.433 回答
0

--如果文件夹名称总是一个字符

select 
LEFT(folder,CHARINDEX('r\',folder)+2) as folder_group
,SUM(size) as sumsize
from #mytable
GROUP BY
LEFT(folder,CHARINDEX('r\',folder)+2)

--如果文件夹名称有可变长度

select 
CASE WHEN CHARINDEX('\',folder,CHARINDEX('\',folder,CHARINDEX('\',folder)+1)+1) = 0 THEN folder
    ELSE LEFT(folder,CHARINDEX('\',folder,CHARINDEX('\',folder,CHARINDEX('\',folder)+1)+1) -1) END AS folder_group
,SUM(size) as sumsize
from #mytable
GROUP BY
CASE WHEN CHARINDEX('\',folder,CHARINDEX('\',folder,CHARINDEX('\',folder)+1)+1) = 0 THEN folder
    ELSE LEFT(folder,CHARINDEX('\',folder,CHARINDEX('\',folder,CHARINDEX('\',folder)+1)+1) -1) END 
于 2012-06-07T14:41:57.290 回答