我目前有一个查询,它在WHERE子句中为应用程序选择多行数据:
SELECT
APP_NAME,
NAME,
ROLE
FROM APP_PERSON
WHERE APP_NAME='ABCD'
ORDER BY APP_NAME,NAME
返回:
ABCD Bob Executive Director
ABCD Kim Director
ABCD Sara Associate Director
ABCD Tim VP
我想要的是返回一行,标题为“角色”的人最少。订单如下:副总监,董事,执行董事,副总裁(这是唯一的选择)。
因此,对于上面的示例,我想要返回的唯一行是:
ABCD Sara Associate Director
如果没有副主任,我想要主任。如何创建执行此操作的查询。我假设某种解码,但不知道该去哪里。谢谢你的帮助!
答案 0 :(得分:2)
解决这个问题的方法不止一种。我更愿意明确加入优先级,然后使用row_number()
选择您想要的行:
select app_name, name, role
from (SELECT APP_NAME, NAME, ROLE,
ROW_NUMBER() over (partition by app_name order by priority) as seqnum
FROM APP_PERSON p join
(select 'Associate Director' as role, 1 as priority from dual union all
select 'Director', 2 from dual union all
select 'Executive Director', 3 from dual union all
select 'VP', 4 from dual
) r
on p.role = r.role
) t
WHERE APP_NAME='ABCD' and seqnum = 1
ORDER BY APP_NAME, NAME
答案 1 :(得分:0)
订单:副总监,董事,执行董事,副总裁(这些是唯一的选择)
我希望下面的查询能为您提供答案。
SELECT
APP_NAME,
NAME,
ROLE
FROM APP_PERSON
WHERE APP_NAME='ABCD'
ORDER BY APP_NAME,NAME
where rownum = 1
order by ROLE
答案 2 :(得分:0)
如何使用这样的公用表表达式:
WITH cte AS (
SELECT
app_name
,name
,role
,MIN(CASE role
WHEN 'Associate Director' THEN 1
WHEN 'Director' THEN 2
WHEN 'Executive Director' THEN 3
WHEN 'VP' THEN 4) AS role_level
FROM app_person
WHERE app_name='ABCD'
)
SELECT
r.*
FROM cte r
INNER JOIN (
SELECT
name
,MIN(role_level) AS role_level
FROM cte rl
GROUP BY name) ON r.name = rl.name AND r.role_level = rl.role_level
ORDER BY
r.app_name
,r.name