SSRS - 分组 - 文件夹层次结构

时间:2017-06-23 12:29:47

标签: sql-server ssrs-2008

我的数据如下表所示, 表名:tblFolder

FolderId | FolderName | ParentFolderId
1        | A          | Null
2        | B          | 1
3        | C          | 2
4        | D          | Null
5        | E          | 4

ParentFolderId将FolderId作为ex的父文件夹。文件夹A是文件夹B的父级

我想以下列格式显示上述数据是SSRS报告。

-A
 -B
  -C
-D
 -E

所以我的问题是以上述格式显示报告应该是我的SQL查询或应该遵循什么方法? 我不希望使用递归层次结构我想通过使用列分组来实现它

2 个答案:

答案 0 :(得分:0)

我们可能需要使用CTE并使用字符串替换工作,如下所示:

;With cte as 
(
    Select *, convert(varchar(10), Concat('-',FolderName)) as Levl from #Folder where ParentFolderId is null

    Union all

    Select f.Folderid, f.FolderName, f.ParentFolderId, convert(varchar(10),concat(' ',Replace(c.Levl, right(c.levl,len(f.folderName)),f.folderName))) as Levl from cte c inner join #Folder f
        on c.Folderid = f.ParentFolderId
)
select Levl from cte
order by Folderid

输出如下:

    +------+
    | Levl |
    +------+
    | -A   |
    |  -B  |
    |   -C |
    | -D   |
    |  -E  |
    +------+

答案 1 :(得分:0)

以下是标准的递归cte,但我们添加了生成的序列以确保正确的呈现顺序/嵌套

- 调整为2008年 -

示例

Declare @YourTable Table ([FolderId] varchar(50),[FolderName] varchar(50),[ParentFolderId] varchar(50))
Insert Into @YourTable Values 
 (1,'A',NULL)
,(2,'B',1)
,(3,'C',2)
,(4,'D',NULL)
,(5,'E',4)

Declare @Top    int         = null      --<<  Sets top of Hier Try 2 
Declare @Nest   varchar(25) = '|-----'  --<<  Optional: Added for readability

;with cteP as (
      Select Seq  = cast(10000+Row_Number() over (Order by FolderName) as varchar(500))
            ,FolderId
            ,ParentFolderId 
            ,Lvl=1
            ,FolderName 
      From   @YourTable 
      Where  IsNull(@Top,-1) = case when @Top is null then isnull(ParentFolderId ,-1) else FolderId end
      Union  All
      Select Seq  = cast(p.Seq+'.'+cast(10000+Row_Number() over (Order by r.FolderName) as varchar(25) )  as varchar(500))
            ,r.FolderId
            ,r.ParentFolderId 
            ,p.Lvl+1
            ,r.FolderName 
      From   @YourTable r
      Join   cteP p on r.ParentFolderId  = p.FolderId)
Select A.FolderId
      ,A.ParentFolderId 
      ,A.Lvl
      ,FolderName = Replicate(@Nest,A.Lvl-1) + A.FolderName
 From cteP A
 Order By Seq

<强>返回

FolderId    ParentFolderId  Lvl  FolderName
1           NULL            1    A
2           1               2    |-----B
3           2               3    |-----|-----C
4           NULL            1    D
5           4               2    |-----E