Sql 如何在oracle中对单个搜索结果使用ORDER BY?
我在oracle中做了一个小查询,以一种方式显示搜索结果,首先在开始时匹配WHEN子句结果,最后在结束时匹配WHEN子句结果。现在我想对第一个匹配的结果按DESC顺序进行排序,其余结果按升序进行排序 下面是使用的示例数据Sql 如何在oracle中对单个搜索结果使用ORDER BY?,sql,oracle,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');
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非常陌生):
但是这个查询正在对所有结果进行排序。如何对个人结果进行排序,建议将不胜感激。这里有一种方法。请注意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 CASE WHEN MATCHRESULT = 1 THEN ZIP END DESC NULLS LAST,
CASE WHEN MATCHRESULT = 2 THEN PLACE END,
CASE WHEN MATCHRESULT = 3 THEN TITLE END
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
非常感谢你的帮助
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