如何获取定义为同一行中单独行的子项类别 table

How to get category of sub items defined as a separate row in the same table

我在 SQL Server 2017 中有一个 table,如下所示:

Type Description
H    General Income
H    Property Income
R    Rent
R    Parking
R    Storage
H    Cash Flow 
H    Other Income
R    Specials

这里H指的是Header,R指的是Role。这些角色属于在它们上面定义的 header。例如,General Income 尚未定义角色,但 Property Income 下有三个角色 - rentparkingstorage.

我的预期输出是:

Header             RoleDescription
General Income    
Property Income    Rent
Property Income    Parking
Property Income    Storage
Cash Flow
Other Income       Specials

我怎么能找到这个,我没找到。任何帮助将不胜感激。

编辑:我有一个 ID 列,是的,我相信我可以用它来订购。

假设您的 table 有一个排序列,您可以通过使用累积条件和来定义组来解决这个问题。

然后还有一招。对角色使用条件聚合,对 header:

使用 window 函数的条件聚合
select max(max(case when type = 'H' then description end)) over (partition by grp) as header,
       max(case when type = 'R' then description end) as role
from (select t.*,
             row_number() over (partition by type, grp order by <ordering col) as seqnum
      from (select t.*,
                   sum(case when type = 'H' then 1 else 0 end) over (order by <ordering col>) as grp
            from t
           ) t
     ) t
group by seqnum
order by grp, seqnum;