获取子行及其顶部根行,并以特殊方式组合ID和名称

时间:2017-08-10 07:56:34

标签: sql sql-server

当我发送CatelogID时,需要使用rootcatelogName和RootCatelogID获取catelogID

    Dim strTemp As String

    strTemp = ActiveSheet.Range("A1").Value

    strTemp = ActiveSheet.Range("A1").Value2

当我将CatelogID设为6时,输出应该是这样的

O / P:

CREATE TABLE catelog 
 (
 CatelogID BIGINT IDENTITY(1,1),
 CatelogName NVARCHAR(50) NOT NULL,
 ParentID BIGINT NULL
 )

SELECT * from catelog

INSERT INTO catelog(catelogName,ParentID)
VALUES('Embedded Sytem',NULL),
('Library',NULL),
('Books',2),
('Pages',3),
('Chapters',4),
('Paragraph',5),
('New Sytem',1),
('College',NULL)

如果我没有传递任何值,我可以得到像这样的结果

CatelogID  RootCatelogName RootParentID 

  2          Library        NULL
  6          Library        2

2 个答案:

答案 0 :(得分:1)

尝试层次结构CTE

DECLARE @id INT = 6;

WITH h AS (
  SELECT CatelogID,catelogName,ParentID
  FROM catelog
  WHERE CatelogID = @id
  UNION ALL
  SELECT p.CatelogID,p.catelogName,p.ParentID
  FROM h
  JOIN catelog p ON p.CatelogID = h.ParentID
)
SELECT t.* 
FROM h
CROSS APPLY (
  SELECT @ID AS catelogID, catelogName AS RootCatelogName, CatelogID AS RootParentID 
  UNION 
  SELECT CatelogID, catelogName AS RootCatelogName, ParentID AS RootParentID 
  ) t
WHERE ParentID IS NULL;

返回

    catelogID   RootCatelogName RootParentID
        2       Library         NULL
        6       Library         2

修改

回答第二个问题的查询

WITH h AS (
  SELECT CatelogID AS leafId, CatelogID, catelogName, ParentID
  FROM catelog
  WHERE ParentID IS NOT NULL
  UNION ALL
  SELECT h.leafId, p.CatelogID, p.catelogName, p.ParentID
  FROM h
  JOIN catelog p ON p.CatelogID = h.ParentID
)
SELECT leafId AS catelogID, catelogName AS RootCatelogName, CatelogID AS RootParentID 
FROM h
WHERE ParentID IS NULL
UNION ALL
SELECT CatelogID,catelogName,ParentID
FROM catelog
WHERE ParentID IS NULL
ORDER BY CatelogID;

返回

catelogID   RootCatelogName RootParentID
    1       Embedded Sytem  NULL
    2       Library         NULL
    3       Library         2
    4       Library         2
    5       Library         2
    6       Library         2
    7       Embedded Sytem  1
    8       College         NULL

答案 1 :(得分:0)

使用递归CTE和row_number来获得最高级别:

declare @CatelogID BIGINT = 6;

;with cte as 
( 
    select CatelogID as BaseCatelogID, CatelogName as BaseCatelogName, 0 as level, CatelogID, CatelogName, ParentID 
    from catelog t
    where CatelogID = @CatelogID

    union all

    select cte.BaseCatelogID, cte.BaseCatelogName, level + 1, t.CatelogID, t.CatelogName, t.ParentID 
    from cte
    join catelog t on (cte.ParentID = t.CatelogID)
)
, cte2 as
(
    select *, row_number() over (partition by BaseCatelogID order by level desc) as rn 
    from cte
)
select CatelogID, CatelogName as RootCatelogName, ParentID as RootParentID
from cte2 where rn = 1
union all
select BaseCatelogID, CatelogName, CatelogID
from cte2 where rn = 1;

返回:

CatelogID  RootCatelogName RootParentID 
  2          Library        NULL
  6          Library        2