如何在oracle中使用ORDER BY进行个别搜索?

时间:2012-09-24 21:24:31

标签: sql oracle

我在oracle中做了一个小查询,以一种方式显示搜索结果,该方式首先匹配WHEN子句结果,最后匹配WHEN子句结果。现在我想按DESC顺序排序第一个匹配的结果,剩余的结果按升序排列。

以下是使用的示例数据。

CREATE table test(id int, title varchar(50), place varchar(20), 
postcode varchar(20));
insert into test values(1,'gatla51','hyd','31382');
insert into test values(2,'sekhar91','kanigiri','91982');
insert into test values(3,'ravi32','ongole','41482');
insert into test values(4,'reddy42','guntur','31281');

这是我所做的查询(当然有些人帮助我,因为我对甲骨文很新):

select title, place, postcode
from (select title, place, postcode,
             (case when postcode like '%9%' then 1
                   when place LIKE '%9%' then 2
                   when title LIKE '%9%' then 3
                   else 0
              end) as matchresult
      from test
     ) d
where matchresult > 0
order by CASE WHEN postcode LIKE %9% THEN ZIP END DESC

但是这个查询正在对所有结果进行排序。我如何评估个人结果,建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

select title, place, postcode
from (select title, place, postcode,
             (case when postcode like '%9%' then 1
                   when place LIKE '%9%' then 2
                   when title LIKE '%9%' then 3
                   else 0
              end) as matchresult
      from test
     ) d
where matchresult > 0
order by CASE WHEN MATCHRESULT = 1 THEN ZIP END DESC NULLS LAST,
         CASE WHEN MATCHRESULT = 2 THEN PLACE END,
         CASE WHEN MATCHRESULT = 3 THEN TITLE END

答案 1 :(得分:1)

这是一种方法。注意ORDER BY子句:

select title, place, postcode
from (select title, place, postcode,
             (case when postcode like '%9%' then 1
                   when place LIKE '%9%' then 2
                   when title LIKE '%9%' then 3
                   else 0
              end) as matchresult                 
      from test
     ) d
where matchresult > 0
order by matchresult,
         (case when matchresult = 1 then postcode end) desc,
         (case when matchresult = 2 then place
               when matchresult = 3 then title
          end) asc