0

最初に 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

しかし、このクエリはすべての結果を並べ替えています。個々の結果を並べ替えるにはどうすればよいですか。提案をいただければ幸いです。

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

これが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 に答える