【问题标题】:SQL SELECT Parent-Child with SORT (...again)SQL SELECT Parent-Child with SORT (...再次)
【发布时间】:2018-11-26 11:11:32
【问题描述】:

更新: 我有一个简单的一级父子关系表,包含以下列:

ID_Asset| Parent_ID_Asset | ProductTitle

我需要按父级后跟子级分组的输出,并且还按父级和子级名称排序。我在小提琴中的尝试。

详情请看这里:https://rextester.com/PPCHG20007

想要的顺序:

9   8   NULL  ADONIS Server
7   16  8     ADONIS Designer
8   20  8     ADONIS Portal Module “Control & Release” Package XS

父母优先,然后是孩子,而 ProductTitle 按字母顺序排列。

到目前为止,感谢所有提示。

【问题讨论】:

  • 先按层级排序,再按ProductTitle。
  • 试过了,要么它没有产生我需要的东西,要么我不确定如何正确地做......
  • 您能告诉我们您期望 Fiddle 中结果的顺序吗?
  • 帖子已更新,谢谢。

标签: tsql sql-order-by parent-child coalesce


【解决方案1】:

我会改为条件排序:

select t.*
from table t
order by (case when parent_id is null then id else parent_id end), ProductTitle;

我假设您需要根据父子关系对数据进行排序。

【讨论】:

  • 嗨,Yogesh,谢谢,经过测试但不起作用,请看小提琴。
【解决方案2】:

据我了解,您需要对根产品的名称进行排序,在它们之间显示子产品,按名称排序,在它们之间显示它们的子产品等。

我猜你正在使用递归 cte。您可以定义一个“层次排序”助手,它是当前级别中的填充数字,并且对于每个深度级别,添加一个带有当前级别中填充数字的后缀,等等。

类似的东西:

declare @Products table(ID int, Parent_ID int, ProductTitle varchar(100))
insert into @Products values
(1,    NULL,        'ADONIS'),
(2,    NULL,        'BACARAT'),
(3,    1,           'Portal Module'),
(4,    1,           'Alhambra'),
(5,    NULL,        'ZULU'),
(6,    2,           'Omega')


; with cte as (
select ID, Parent_ID, ProductTitle, FORMAT(ROW_NUMBER() over(order by ProductTitle), '0000') as SortingHelper
from @Products
where Parent_ID is null
union all
select p.ID, p.Parent_ID, p.ProductTitle, cte.SortingHelper + '.' + FORMAT(ROW_NUMBER() over(order by p.ProductTitle), '0000') as SortingHelper
from @Products p
inner join cte on cte.ID = p.Parent_ID
)

select ID, Parent_ID, ProductTitle
from cte
order by SortingHelper

【讨论】:

    【解决方案3】:

    我认为这是您正在寻找的顺序。这会将每一行连接到其父行(如果存在)。然后如果有一个 TP(父)记录,那就是父标题、ID 等,否则当前记录必须是父记录。为了清楚起见,我在查询结果中显示了父名称。然后排序

    • 父母姓名(因此父母和孩子在一起,但按父母姓名顺序)
    • 家长 ID(如果两个或多个家长的姓名/头衔相同,这将使孩子与正确的家长保持一致)
    • 一个标志,0 代表父母,1 代表孩子,所以父母优先
    • 当前记录名称,将按名称/标题顺序对子项进行排序

    代码是

    Select T.*, 
        isnull(TP.ProductTitle, T.ProductTitle) as ParentName  -- This is the parent name, shown for reference
    from test T
        left outer join Test TP on TP.ID_Asset = T.Parent_ID_Asset  --This is the parent record, if it exists
    ORDER BY isnull(TP.ProductTitle, T.ProductTitle),  --ParentName sort
        isnull(TP.ID_Asset, T.ID_Asset),  --if two parents have the same title, this makes sure they group with their correct children
        Case when T.Parent_ID_Asset is null then 0 else 1 end,  --this makes sure the parent comes before the child
        T.ProductTitle  --Child Sort
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      相关资源
      最近更新 更多