父母,子女,子子女CTE

时间:2019-05-31 04:04:01

标签: sql sql-server

这是我创建的CTE,用于获取父帐户,子帐户和子帐户,但顶部显示了四个父项。

with AccountCTE(Id,Code,AccountName,[Level])
as
(
  select D.Id, D.Code, D.AccountName, 1
  from DefaultAccount D
  join AccountClass on D.AccountClassId = AccountClass.Id
  where D.ParentAccountId Is Null
  union All
  select Da.Id, Da.Code, Da.AccountName, AccountCTE.Level +1
  from DefaultAccount Da
  join AccountCTE on Da.ParentAccountId = AccountCTE.Id
)
select * from AccountCTE

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试一下作为解决方案...

这里tab是表名Id是您的rowId,parentid是您的parentId。

  ;WITH CTE AS (
      SELECT Id, ParentId,0 AS [Level], CAST(Id AS varchar(1000)) AS Heirarchy,Id AS TopParentId
      FROM dbo.tab
      WHERE Id IN (SELECT Id FROM tab WHERE ParentId IS NULL)
      UNION ALL

      SELECT mgr.Id, mgr.ParentId, CTE.[Level] +1 AS [Level], 
            CAST(( CAST(mgr.Id AS VARCHAR(1000)) + '>' + CTE.Heirarchy) AS varchar(1000)) AS Heirarchy, CTE.TopParentId
      FROM CTE
        INNER JOIN dbo.tab AS mgr
          ON CTE.Id = mgr.ParentId
    )
    select * from cte order by heirarchy