将类别列表转换为类别树 Table SQL

Convert List of Categories into Category Tree Table SQL

我有一个 table 看起来像这样:

CatID   ParentID
1       0
2       1
3       2
4       3
5       0
6       1
7       2

这是我想要达到的结果:

Cat0   Cat1   Cat2   Cat3   Cat4   Cat5   Cat6   Cat7
1      2      3      4
5      6      7

我该怎么做?我考虑过创建一个临时文件 table,但不知道如何用所需格式的数据填充它。

有人可以帮忙吗?

带有 CatID 的 table 很长 - 有 54K 个唯一的 CatID。

Actual list of CatIDs in excel

我想我明白了。您可以使用条件聚合来做到这一点:

select max(case when parentid = 0 then catid end) as cat0,
       max(case when parentid = 1 then catid end) as cat1,
       max(case when parentid = 2 then catid end) as cat2,
       . . .
from (select t.*,
             row_number() over (partition by parentid order by catid) as seqnum
      from t
     ) t
group by seqnum;

这里是rextester.