【问题标题】:How to Sort records in SQL like in a parent child order如何像父子顺序一样对SQL中的记录进行排序
【发布时间】:2018-10-13 08:17:32
【问题描述】:

我有一个包含“ItemId”和“ParentItemId”列的表。我希望按父子顺序对结果进行排序。有了这个,还有其他列需要对数据进行排序。 我希望首先根据“itemType”对数据进行排序。

例如。

 AutoId | itemId | parentItemId | itemType
   1        1       0               3
   2        2       null            4
   3        3       0               6
   4        4       null            5
   5        5        1              9
   6        6        2              9
   7        7        3              9
   8        8        4              9
   9        9        0              2
   10       10       0              1

现在我希望按以下格式绘制结果

 AutoId | itemId | parentItemId | itemType
   10       10        0              1
   9        9         0              2
   1        1         0              3
   5        5         1              9
   2        2        null            4
   6        6         2              9
   4        4        null            5
   8        8         4              9
   3        3         0              6 
   7        7         3              9

有没有办法像这样对记录进行排序?

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: sql sorting columnsorting


    【解决方案1】:

    你可以这样做:

    select *
    from table1
    order by coalesce(parentitemid,itemid), itemid
    

    示例:http://sqlfiddle.com/#!9/32e58e/2

    【讨论】:

    • 这假设父母的itemid总是小于孩子的itemid,但这似乎是一个合理的假设。
    【解决方案2】:

    对于 MySql,使用 ifnull 作为 parentItemId 字段 喜欢

    select *
    from table
    order by IFNULL(parentItemId, itemId), itemId
    

    对于甲骨文

    select *
    from table
    order by NVL(parentItemId, itemId), itemId
    

    【讨论】:

      【解决方案3】:

      取自@hkutluay 对 SQL Server 的回答:

      select * from table1 order by ISNULL(parentItemID, ItemID), ItemID

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多