带有聚合函数的Oracle子选择查询

时间:2010-12-01 08:26:00

标签: oracle aggregate-functions subquery

    ID  FirstName   LastName 
1   John        Smith    
2   Mike        Smith 
3   Ben         Bray 
4   John        Bray 
5   John        Smith 
6   Bill        Lynch 
7   Bill        Smith 
你好。我正在尝试使用MIN和MAX函数在oracle中进行子选择查询,但我似乎无法走上正确的轨道。任何帮助将不胜感激。

例子:我正在寻找Carl Brayland的餐桌。 如果他不存在我想在Carl Brayland之前得到第一个名字,它会给我ID 3 - >本布雷

示例2:我正在寻找Mike Mad的表格 如果他不存在,我想在Mike Mad之前获得名字,这将给我ID 6 - >比尔林奇

姓氏应该是领先的。

1 个答案:

答案 0 :(得分:0)

在排序集上使用ROWNUM(此处为:p_lastname := 'Mad'; :p_firstname := 'Mike';):

SQL> WITH my_data AS (
  2     SELECT 1 ID, 'John' FirstName, 'Smith' LastName FROM DUAL
  3     UNION ALL SELECT 2, 'Mike', 'Smith' FROM DUAL
  4     UNION ALL SELECT 3, 'Ben' , 'Bray'  FROM DUAL
  5     UNION ALL SELECT 4, 'John', 'Bray'  FROM DUAL
  6     UNION ALL SELECT 5, 'John', 'Smith' FROM DUAL
  7     UNION ALL SELECT 6, 'Bill', 'Lynch' FROM DUAL
  8     UNION ALL SELECT 7, 'Bill', 'Smith' FROM DUAL
  9  )
 10  SELECT id, firstname, lastname
 11    FROM (SELECT id, firstname, lastname
 12             FROM my_data
 13            WHERE lastname <= :p_lastname
 14              AND (lastname < :p_lastname OR firstname <= :p_firstname)
 15            ORDER BY lastname DESC, firstname DESC)
 16   WHERE ROWNUM = 1;

        ID FIRSTNAME LASTNAME
---------- --------- --------
         6 Bill      Lynch