如何在Oracle Query中组合SELECT DISTINCT和ROWNUM

时间:2015-07-14 18:45:45

标签: sql oracle

如果可能,我需要将下面的两个MySQL语句合并到一个ORACLE查询中。

初始查询是

SELECT DISTINCT FIRST_NAME FROM PEOPLE WHERE LAST_NAME IN ("Smith","Jones","Gupta")

然后根据每个FIRST_NAME返回我的查询

SELECT * 
FROM PEOPLE 
WHERE FIRST_NAME = {FIRST_NAME} 
  AND LAST_NAME IN ("Smith","Jones","Gupta") 
ORDER BY FIELD(LAST_NAME, "Smith","Jones","Gupta") DESC 
LIMIT 1

"姓氏列表"作为"默认/覆盖"指示符,所以每个名字只有一个人,并且同一名字的多行存在,只有"姓氏"的列表中的最后一个匹配。使用。

我需要一个SQL查询,它返回" in"的最后一行。基于IN(a,b,c)中值的顺序的子句。这是一个示例表,以及我从查询中得到的结果。

对于表PEOPLE,值为

LAST_NAME    FIRST_NAME
.....
Smith        Mike    
Smith        Betty
Smith        Jane
Jones        Mike
Jones        Sally
....

我需要一个基于DISTINCT FIRST_NAME和LAST_NAME IN('史密斯'琼斯')的查询返回

Betty Smith
Jane Smith
Mike Jones
Sally Jones

2 个答案:

答案 0 :(得分:3)

你可以这样做:

select first_name, last_name
from (
  select p.first_name,
         p.last_name,
         row_number() over (partition by p.first_name
                            order by case p.last_name
                                     when 'Smith' then 1
                                     when 'Jones' then 2
                                     when 'Gupta' then 3
                                     end desc) as rn
  from people p
  where p.last_name in ('Smith','Jones','Gupta')
)
where rn = 1;

演示:SQL Fiddle

修改

获得更多专栏并不难。我确定你可以用更多的努力想出来:

select *
from (
  select p.*,
         row_number() over (partition by p.first_name
                            order by case p.last_name
                                     when 'Smith' then 1
                                     when 'Jones' then 2
                                     when 'Gupta' then 3
                                     end desc) as rn
  from people p
  where p.last_name in ('Smith','Jones','Gupta')
)
where rn = 1;

答案 1 :(得分:3)

或者像这样:

select first_name, 
       max(last_name) 
           keep (dense_rank first order by decode(last_name,
                                                  'Smith', 1,
                                                  'Jones', 2,
                                                  'Gupta', 3) desc)
 group by first_name

Oracle" FIRST" /"最后"函数允许从具有最大/最小值的行的其他列获取值(例如,获取具有最大薪水的员工的last_name,或者在这种情况下,从具有最大等级的行获取last_name)
http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions056.htm