0

我在 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');

这是我所做的查询(当然有人帮助,因为我对 oracle 很陌生):

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

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

4

2 回答 2

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
于 2012-09-24T21:34:14.473 回答
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
于 2012-09-24T21:35:14.940 回答