代码之家  ›  专栏  ›  技术社区  ›  James

用于检索组中某个点的最高项的SQL查询

  •  0
  • James  · 技术社区  · 16 年前

    最好的描述方法是我有一张表,上面列有他们的名字和年龄。假设同姓的人来自同一个家庭。我需要在Oracle中查询,它将检索每个家庭中最年长的人的列表,但不超过某个年龄。

    表:人

    name      surname         age
    ===============================
    James     Smith           23
    Sarah     Powell          17
    Barry     Smith           31
    Mark      Smith           35
    Mary      Smith           18
    Bob       Powell          30
    

    我该如何找回30岁以下的每个家庭中最年长的人?

    我追求的结果

    name      surname         age
    ===============================
    James     Smith           23
    Sarah     Powell          17
    
    3 回复  |  直到 15 年前
        1
  •  3
  •   D'Arcy Rittich    16 年前
    select p.*
    from person p
    inner join (
        select surname, max(age) as maxage
        from person 
        where age < 30
        group by surname
    ) pm on p.surname = pm.surname and p.age = pm.maxage
    
        2
  •  0
  •   Jeffrey Kemp    16 年前

    此版本只需要传递一次数据:

    SELECT DISTINCT
           FIRST_VALUE(name)
           OVER (PARTITION BY surname ORDER BY age DESC) name
          ,FIRST_VALUE(surname)
           OVER (PARTITION BY surname ORDER BY age DESC) surname
          ,FIRST_VALUE(age)
           OVER (PARTITION BY surname ORDER BY age DESC) age
    FROM   person
    WHERE  age < 30;
    

    警告:如果打领带(即同一家庭中两个年龄相同的人),只会选一条。

        3
  •  0
  •   Stellios    16 年前

    创建表F(姓名varchar2(32),姓氏varchar2(32),年龄编号);

    在f值中插入(‘james’,‘smith’,23);

    在f值中插入(‘Sarah’,‘Powell’,17);

    在f值中插入(“barry”,“smith”,31);

    在f值中插入(‘mark’,‘smith’,35);

    在f值中插入(‘mary’,‘smith’,18);

    插入f值(“bob”,“powell”,30);

    选择*来自 (选择 姓名, 姓, 年龄, 密级(按姓氏顺序按年龄描述划分) 从f 年龄30岁) 其中d_秩=1;

    姓名年龄等级


    莎拉·鲍威尔17 1

    詹姆斯史密斯23 1

    另请参见:

    http://www.oracle.com/technology/oramag/oracle/07-jan/o17asktom.html