【问题标题】:Ordering SQL query by hierarchy and it's random code按层次排序 SQL 查询和它的随机代码
【发布时间】:2020-03-13 18:57:41
【问题描述】:

我尝试搜索相关和相似的内容,但是找不到。

这是我需要得到的表格:

+-----+-----------+------+-------------------+
| ID  | PARENT_ID | CODE |       NAME        |
+-----+-----------+------+-------------------+
| 218 | NULL      | 1445 | First One         |
| 235 | 218       |    2 | First Child       |
| 247 | 235       |   45 | First Grandchild  |
| 246 | 235       |   55 | Second Grandchild |
| 230 | 218       |    3 | Second Child      |
| 238 | 230       |   12 | Third Grandchild  |
| 231 | 230       |   20 | Fourth Grandchild |
+-----+-----------+------+-------------------+

顺序必须是它的层次结构,然后是它的代码。 我需要这个来做出断言。而且,如果可能的话,我想只做一个查询,而没有对这个列表进行排序的方法。 这是我要断言的示例: Tree Hierarchy

到目前为止我所做的,是以下递归查询:

WITH CTE (ID, PARENT_ID, CODE, NAME)
AS
-- Anchor:
    (SELECT
        ID,
        PARENT_ID,
        CODE,
        NAME
        FROM WAREHOUSE
        WHERE PARENT_ID IS NULL

    UNION ALL 

-- Level:
    SELECT
        W.ID,
        W.PARENT_ID,
        W.CODE,
        W.NAME
        FROM WAREHOUSE AS W
        INNER JOIN CTE
        ON R.PARENT_ID = CTE.ID)

SELECT *
    FROM CTE

感谢您对此提供的任何帮助! 提前致谢!

【问题讨论】:

  • 您的查询中有一个无效的别名。我认为在上面的第二个查询中 R 应该是 W。
  • 您已经展示了结果,但您的源数据是什么样的?
  • 嗨,Delon,我认为包含 WAREHOUSE 和示例数据的 CREATE TABLE DDL 会很有帮助。
  • @RossBush,谢谢!我已经编辑了我的帖子。
  • @Brian,我的源数据正是我发布的结果,但是没有正确的顺序。

标签: sql-server hierarchy


【解决方案1】:

看起来你可以在hierarchyid路径中使用[CODE]序列

示例

Declare @YourTable Table ([ID] int,[PARENT_ID] int,[CODE] varchar(50),[NAME] varchar(50))
Insert Into @YourTable Values 
 (218,NULL,1445,'First One')
,(235,218,2,'First Child')
,(247,235,45,'First Grandchild')
,(246,235,55,'Second Grandchild')
,(230,218,3,'Second Child')
,(238,230,12,'Third Grandchild')
,(231,230,20,'Fourth Grandchild')


;with cteP as (
      Select ID
            ,PARENT_ID 
            ,[Code]
            ,Name 
            ,HierID = convert(hierarchyid,concat('/',[Code],'/'))
      From   @YourTable
      Where  Parent_ID is null
      Union  All
      Select ID  = r.ID
            ,PARENT_ID  = r.PARENT_ID 
            ,r.[Code]
            ,Name   = r.Name
            ,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.[Code],'/'))
      From   @YourTable r
      Join   cteP p on r.PARENT_ID  = p.ID)
Select Lvl   = HierID.GetLevel()
      ,ID
      ,PARENT_ID
      ,[Code]
      ,Name  
 From cteP A
 Order By A.HierID

退货

Lvl ID  PARENT_ID   Code    Name
1   218 NULL        1445    First One
2   235 218         2       First Child
3   247 235         45      First Grandchild
3   246 235         55      Second Grandchild
2   230 218         3       Second Child
3   238 230         12      Third Grandchild
3   231 230         20      Fourth Grandchild

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多