我正在编写一个针对内部数据仓库的基本搜索引擎。
假设我拥有'技能'表,像这样:
EmpID Skills
----- --------------------
1 ,Java,
2 ,Java,,C#,
3 ,C#,,Ruby,
4 ,Java,,C#,,Python,
5 ,Python,,C#,
我需要编写一个搜索技能表的查询,查找匹配项。
如果我正在搜索Java AND C#,我希望看到以下结果:
EmpID Skills Matches
----- ----------------- -------
2 ,Java,,C#, 2
4 ,Java,,C#,,Python, 2
如果我正在搜索Java OR C#,我希望看到这些结果,按照匹配排序:
EmpID Skills Matches
----- ------------------ -------
2 ,Java,,C#, 2
4 ,Java,,C#,,Python, 2
1 ,Java, 1
3 ,C#,,Ruby, 1
5 ,Python,,C#, 1
我如何在SQL(Oracle 11)中编写该查询?
谢谢!
答案 0 :(得分:2)
with
test_data ( empid, skills ) as (
select '1', ',Java,' from dual union all
select '2', ',Java,,C#,' from dual union all
select '3', ',C#,,Ruby,' from dual union all
select '4', ',Java,,C#,,Python,' from dual union all
select '5', ',Python,,C#,' from dual
)
-- end of test data; SOLUTION BEGINS BELOW
select empid, skills,
case when skills like '%,Java,%' then 1 else 0 end +
case when skills like '%,C#,%' then 1 else 0 end as matches
from test_data
order by matches desc, empid -- ORDER BY is optional
;