使用同一个表

时间:2017-03-01 20:33:24

标签: sql oracle

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

我已尝试过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,顺便说一句。

感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

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

Texture

答案 1 :(得分:1)

我认为你应该这样做:

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。)

相关问题