根据特定行

时间:2017-10-19 15:58:34

标签: sql sql-server

大家好,我需要你的帮助:

我需要根据一些特定的行在sql server中填充一个额外的列(Directory)。为此,我需要评估列(文件名)并在列(目录)上复制它,直到关键字更改为止。所以原来的表是这样的:

enter image description here

这就是我需要完成的事情:

enter image description here

我可以使用CTE吗?怎么样?

提前致谢!

2 个答案:

答案 0 :(得分:0)

如果directory命名格式与您的样本数据一致,则此处为单向

SELECT id,Filename,
       Directory = Min(Filename)OVER(partition BY grp)
FROM   (SELECT *,
                grp= Sum(CASE WHEN Filename LIKE '-%' THEN 1 ELSE 0 END)
                      OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)               
        FROM   Yourtable) a 

另一种较少依赖于命名约定的方法

SELECT id,
       Filename,
       Directory = Max(iDirectory)OVER(partition BY grp)
FROM   (SELECT Id,
               Filename,
               grp,
               iDirectory=CASE WHEN Row_number() OVER(partition BY grp ORDER BY id) = 1 THEN Filename ELSE NULL END
        FROM   (SELECT *,
                       grp= Sum(CASE WHEN Filename LIKE '-%' THEN 1 ELSE 0 END)
                              OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
                FROM   #test) a)b 

答案 1 :(得分:0)

declare  @tt table (id int identity(1,1), [FileName] varchar(50), DirectoryName varchar(50))
insert into @tt([FileName]) values
('- Directory 1')
,('File a')
,('File b')
,('File c')
,('- Directory 2')
,('File d')
,('File e')
,('File f')
,('File g')

SELECT A.ID, A.[FILENAME],
    (
        SELECT TOP 1 [FILENAME] FROM @TT AS B 
        WHERE [FILENAME] LIKE '- DIRECTORY%'
        AND B.ID <= A.ID
        ORDER BY B.ID DESC
    ) AS DIRECTORYNAME
FROM @TT AS A