SQL帮助-子级-祖父母关系

时间:2019-11-25 13:19:13

标签: sql sql-server stored-procedures hana

我有下表:

+------+--------+-----------+------------------+-----------------+
|  ID  |  Name  | FATHER_ID | Generation Level | Last Generation |
+------+--------+-----------+------------------+-----------------+
|  001 | John   |       003 |                5 | x               |
|  002 | Tim    |       004 |                3 | x               |
|  003 | Max    |       005 |                4 |                 |
|  004 | Jim    |       006 |                2 |                 |
|  005 | Matt   |       004 |                3 |                 |
|  006 | Philip |           |                1 |                 |
|  007 | Tom    |       005 |                  |                 |
|  008 | Brad   |           |                1 |                 |
|  009 | Peter  |       008 |                2 |                 |
| 0010 | Bryan  |       009 |                3 | x               |
| 0011 | Jane   |       009 |                3 | x               |
+------+--------+-----------+------------------+-----------------+

每个人都链接到父亲ID,但ID 006和008却没有父亲,因为他们是第一代。

我想通过sql查询或过程按如下方式将最后一代的大子代与其祖先链接起来。

+-------+---------------+
| Name  | Ancestor Name |
+-------+---------------+
| John  | Max           |
| John  | Matt          |
| John  | Jim           |
| John  | Phillip       |
| Tim   | Jim           |
| Tim   | Phillip       |
| Bryan | Peter         |
| Bryan | Brad          |
| Jane  | Peter         |
| Jane  | Brad          |
+-------+---------------+

0 个答案:

没有答案