【问题标题】:Ordering results with a union from the same table使用同一个表中的并集对结果进行排序
【发布时间】:2017-03-01 20:33:24
【问题描述】:

我需要先在列表中显示一组结果,然后再显示下表中的其余结果。

我尝试过SQL: how to use UNION and order by a specific select?,但在我的情况下似乎不起作用。

我的查询如下所示

SELECT * FROM (
    SELECT id, display as ordered
      FROM table
     WHERE id in (...) --these need to be first
    UNION
    SELECT id, display
      FROM table
     WHERE id not in (...) --these need to be at the end
)
ORDER BY ordered

无论我做什么,我的结果都会按显示顺序返回。

顺便说一句,我正在使用 Oracle。

感谢您的帮助。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    您需要明确包含数字才能获得排序。此查询首先对第一个结果集进行排序,然后对第二个结果集进行排序。在每组中,结果再次按 id 排序。 (如果不需要,请删除它)

    SELECT id,display FROM (
        SELECT id, display,1 as ordered
          FROM table
         WHERE id in (...) --these need to be first
        UNION
        SELECT id, display,2 
          FROM table
         WHERE id not in (...) --these need to be at the end
    )
    ORDER BY ordered,id
    

    【讨论】:

    • @RobM 那你会考虑接受这个答案吗?更多用户将因此受益。
    【解决方案2】:

    我认为你应该这样做:

    select id, display
    from table
    order by (case when id in (. . .) then 1  -- first list
                   when id in (. . .) then 3  -- last list
                   else 2                     -- everything else
              end);
    

    不需要unionunion all。只需一个 order by 表达式。

    如果您不想要所有 id,则应包含 where 子句。

    (我发现您的问题对于列表的构成有点不清楚。如果确实合适,您可以使用not in。)

    【讨论】:

    • ...并且,如果需要,可能添加 id(或其他任何内容)作为辅助排序标准
    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多