【问题标题】:View Level Number on Recursive Table SQL在递归表 SQL 上查看级别编号
【发布时间】:2018-03-28 07:39:34
【问题描述】:

我有下表:

--------------------------------------------
ID      ParentID     Item  
--------------------------------------------
1                    root
2       1            AA
3       1            BB
4       1            CC
5       1            DD
6       2            A1
7       6            A11
ff.

我想得到以下结果:

ID      ParentID     Item         Level
---------------------------------------------
1                    root         0
2       1            AA           1
3       1            BB           1
4       1            CC           1
5       1            DD           1
6       2            A1           2
7       6            A11          3
ff.
  1. 创建新列level 的最佳想法是什么?是创建一个新列并添加一个公式或类似计算或函数的东西吗?
  2. 如何在t-sql 上实现这一目标?

【问题讨论】:

    标签: sql tsql sql-server-2014


    【解决方案1】:

    您将使用递归 CTE:

    with cte as (
          select t.id, t.parentid, t.item, 0 as lvl
          from t
          where parentid is null
          union all
          select t.id, t.parentid, t.item, cte.lvl + 1 as lvl
          from t join
               cte
               on t.parentid = cte.id
         )
    select *
    from cte;
    

    在表中存储这些数据是 . . .麻烦,因为你需要保持更新。您可能只想在需要时即时计算。

    【讨论】:

      【解决方案2】:

      只需使用DENSE_RANK

      DECLARE @YourTable TABLE(ID INT,ParentID VARCHAR(10),Item VARCHAR(10))
      INSERT into @YourTable VALUES(1,' ','root')
      INSERT into @YourTable VALUES(2,'1','AA')
      INSERT into @YourTable VALUES(3,'1','BB')
      INSERT into @YourTable VALUES(4,'1','CC')
      INSERT into @YourTable VALUES(5,'1','DD')
      INSERT into @YourTable VALUES(6,'2','A1')
      INSERT into @YourTable VALUES(7,'6','A11')
      
      
      SELECT ID,ParentID,Item
          ,(DENSE_RANK() OVER(ORDER BY ISNULL(NULLIF(ParentID,''),0)))-1 [Level]
      FROM @YourTable
      

      输出:

      ID  ParentID    Item    Level
      1               root    0
      2   1           AA      1
      3   1           BB      1
      4   1           CC      1
      5   1           DD      1
      6   2           A1      2
      7   6           A11     3
      

      希望对你有帮助。

      【讨论】:

      • 尝试添加两行,(8,' ','A12'), (9,'8','A12')。为什么会有人使用不同类型的 id 和 parent?
      猜你喜欢
      • 2012-10-21
      • 2012-02-21
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 2010-11-03
      相关资源
      最近更新 更多