0

我目前有一个查询,它在 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

如果没有副主任,我会想要主任。如何创建一个可以执行此操作的查询。我假设某种解码,但不知道去哪里用它。谢谢你的帮助!

4

3 回答 3

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
于 2013-04-16T13:52:47.270 回答
0

顺序是:副主任、主任、执行主任、副总裁(这些是唯一的选择)

我希望下面的查询将为您提供答案。

SELECT
    APP_NAME,
    NAME,
    ROLE
FROM APP_PERSON
WHERE APP_NAME='ABCD'
ORDER BY APP_NAME,NAME
where rownum = 1
order by ROLE
于 2013-04-16T13:51:14.150 回答
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
于 2013-04-16T14:11:18.143 回答