最初に WHEN 句の結果が最初に一致し、最後に WHEN 句の結果が最後に一致するように検索結果を表示するために、Oracle で小さなクエリを実行しました。ここで、最初に一致した結果を 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
しかし、このクエリはすべての結果を並べ替えています。個々の結果を並べ替えるにはどうすればよいですか。提案をいただければ幸いです。