SQL Server层次结构一行到多列查询

时间:2015-04-22 09:44:38

标签: sql sql-server hierarchy

我有一个结构和记录表,如下

ID          | Name                      |
-----------------------------------------
01          | Group Category            |
0101        | Category One              |
010101      | Category One Sub          |
01010101    | Category One Sub Sub      |
010102      | Category One Sub Two      |
01010201    | Category One Sub Sub Two  |
0102        | Category Two              |
010201      | Category Two Sub          |
01020101    | Category Two Sub Sub      |
0103        | Category Three            |
010301      | Category Three Sub        |
01030101    | Category Three Sub Sub    |
-----------------------------------------

如何使用SQL Server生成查询结果,如下所示。

Column1         | Column2       | Column3               | Column4                   |
-------------------------------------------------------------------------------------
Group Category  | Category One  | Category One Sub      | Category One Sub Sub      |
-------------------------------------------------------------------------------------
Group Category  | Category One  | Category One Sub Two  | Category One Sub Sub Two  |
-------------------------------------------------------------------------------------
Group Category  | Category Two  | Category Two Sub      | Category Two Sub Sub      |
-------------------------------------------------------------------------------------
Group Category  | Category Three| Category Three Sub    | Category Three Sub Sub    |
-------------------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

使用如图所示的表结构,如果级别数是固定的,您可以使用LIKE ID列简单地自连接多次作为连接条件:

  seekOpq.setMax(100);
      and
    seekTxt.setText(currLevel);

这应该可以提供所需的输出。