我需要从扩展名中拆分文件名,并将它们放在不同的列中。
然后我需要将目录全部按目录滚动,其他字段包含该文件夹中所有文件扩展名的逗号分隔列表。
这是我到目前为止所做的:
select
Length,
(case when Name like '%.%'
then (left((Name), charindex('.', (Name)) - 1))
else ''
end) as FileName
,(case when Name like '%.%'
then reverse(left(reverse(Name), charindex('.', reverse(Name)) - 1))
else ''
end) as Extension
,Directory
FROM dbo.[SourceRetail-V1]
WHERE Mode not like 'd--%'
order by Directory asc
的问题:
以下是文字来源:
Mode Length Name Directory
-a--- 78497 BSAS.map.xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4329 T052.tf.sql Y:\Data\Retail\BQ\Maps\SAP
-a--- 24268 T052.map.txt Y:\Data\Retail\BQ\Maps\SAP
-a--- 53837 PAYR.map.xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4321 LFB1.tf.xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 146089 BSAK.map.xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4322 LFA1.tf.xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4325 LFC1.tf.xml Y:\Data\Retail\BQ\Maps\SAP
中介表:
Mode Length Name Extension Directory
-a--- 78497 BSAS.map xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4329 T052.tf sql Y:\Data\Retail\BQ\Maps\SAP
-a--- 24268 T052.map txt Y:\Data\Retail\BQ\Maps\SAP
-a--- 53837 PAYR.map xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4321 LFB1.tf xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 146089 BSAK.map xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4322 LFA1.tf xml Y:\Data\Retail\BQ\Maps\SAP
-a--- 4325 LFC1.tf xml Y:\Data\Retail\BQ\Maps\SAP
最终产品:
Mode Length Directory Extensions
a---- 319998 Y:\Data\Retail\BQ\Maps\SAP xml,sql,txt
答案 0 :(得分:1)
对于第一个查询,您可以使用
select substring([FileName], 0, len([FileName])- charindex('.', reverse([FileName]))+1)
from tablename
对于第二个问题,您可以使用For XML Path / STUFF来连接所有扩展
答案 1 :(得分:1)
尝试使用STUFF来制作扩展名列表。
select distinct
Directory,
Ext = STUFF(( SELECT distinct
case when t2.Name like '%.%'
then ' | '+ reverse(left(reverse(t2.Name), charindex('.',reverse(t2.Name))-1))
else ''
end
FROM @T t2
WHERE t2.Directory = t1.Directory
ORDER BY 1
FOR XML PATH('')), 1, 3, '')
from @T t1
答案 2 :(得分:1)
我只将两条记录粘贴到示范表变量中,但这应该可以。
Declare @YourTable table (Mode varchar(50),Length int,Name varchar(100),Directory varchar(250))
Insert into @YourTable values
('-a---',78497,'BSAS.map.xml','Y:\Data\Retail\BQ\Maps\SAP'),
('-a---',4329 ,'T052.tf.sql' ,'Y:\Data\Retail\BQ\Maps\SAP'),
('-a---',4329 ,'NoExtension' ,'Y:\Data\Retail\BQ\Maps\SAP')
Select A.Mode
,Length = sum(A.Length)
,A.Directory
,Extensions = max(B.Extensions)
From @YourTable A
Cross Apply (
Select Extensions=Stuff((
Select Distinct ',' + case when CharIndex('.',Name)=0 then 'None' else Right(Name,CharIndex('.',Reverse(Name))-1) end
From @YourTable
Where Directory=A.Directory
Order By 1
For XML Path ('')),1,1,'')
) B
Group By A.Mode,A.Directory
返回
Mode Length Directory Extensions
-a--- 87155 Y:\Data\Retail\BQ\Maps\SAP None,sql,xml