2012-09-24 23 views
0

我已經在oracle中做了一個小的查詢來顯示搜索結果的方式,首先匹配WHEN子句結果在開始和最後匹配的WHEN子句結果。現在我想在DESC順序中排序第一個匹配結果,其餘結果按升序排列。如何使用ORDER BY在oracle中的單個搜索結果?

以下是使用的示例數據。

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 

但這查詢排序的所有結果。我怎麼能個別的結果,建議將不勝感激。

回答

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 
+0

非常感謝你回回你的幫助 – user964147

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 
+0

非常感謝您的回覆 – user964147

相關問題