排序顺序

时间:2018-02-16 17:51:37

标签: oracle

如果标题不符合我的要求,我会道歉。请提出任何建议以帮助改进。

我有一个提取大量列表的SQL代码。在此列表中有许多项目。

Items
--------
Apple
Egg
Cheese
Pear
Goat
Bear
Toad
Horse
Log

客户想要的是始终在底部有几个项目

Items
--------
Apple
Toad
Horse
Log
Egg << always on bottom
Cheese << always on bottom
Pear << always on bottom
Goat << always on bottom
Bear << always on bottom

所以我提出了一个看起来像这个

的case by子句
ORDER BY CASE 
WHEN item= 'Egg' THEN '1'
WHEN item= 'Cheese' THEN '1'
WHEN item= 'Pear' THEN '1'
WHEN item= 'Goat' THEN '1'
WHEN item= 'Bear' THEN '1'
ELSE '0' 
END, 
item ASC

因此,任何不是上述项目的项目都按字母顺序排序,所有其他项目显示在底部。好吧,客户回来说,底部的那些,他们想要按字母顺序排序,只是仍然在底部。

我该怎么做呢?我尝试在END后添加ASC,但似乎没有做到这一点。我也尝试了不同的啄食顺序,比如那么'1',那么'2',那么'3'等等,那也没有做到。

2 个答案:

答案 0 :(得分:2)

如果您在SELECT子句中添加“sort-group”,我认为更容易理解:

SELECT
    item,
    ( CASE
        WHEN item IN ( 'Egg', 'Cheese', 'Pear', 'Goat', 'Bear' )
            THEN 1
        ELSE
            0
    END ) AS sortGroup,
    otherColumns...
FROM
    table
ORDER BY
    sortGroup,
    item

我制作了一个SQLfiddle(针对MySQL,但同样的SQL适用于SQL Server和Oracle):http://www.dynamicdrive.com/forums/showthread.php?45895-How-to-populate-php-html-form-with-MySQL-data

以下是我得到的结果:

item    sortGroup
Apple   0
Horse   0
Log     0
Toad    0
Bear    1
Cheese  1
Egg     1 
Goat    1
Pear    1

这符合您客户的要求:

  

好吧,客户回来说,底部的那些,他们想要按字母顺序排序,只是仍然在底部。

答案 1 :(得分:1)

你的订单接近你所要做的。

SQL> with test (item) as
  2  (select 'apple'  from dual union
  3   select 'egg'    from dual union
  4   select 'cheese' from dual union
  5   select 'pear'   from dual union
  6   select 'goat'   from dual union
  7   select 'bear'   from dual union
  8   select 'toad'   from dual union
  9   select 'horse'  from dual union
 10   select 'log'    from dual
 11  )
 12  select item
 13  from test
 14  order by case when item in ('egg', 'cheese', 'pear', 'goat', 'bear') then '1'
 15                else '0'
 16           end,
 17           item;

ITEM
------
apple
horse
log
toad
bear
cheese
egg
goat
pear

9 rows selected.

SQL>