代码之家  ›  专栏  ›  技术社区  ›  Nathan Lutterman

如何在MySQL中自连接聚合函数的结果?

  •  0
  • Nathan Lutterman  · 技术社区  · 11 年前

    我有以下格式的一些数据:

    Table: MountHeights
    
    ID  | Height| Type  |  ItemCode     |  Context
    --------------------------------------------
    1   | 15    | max   | BD1896-1W     | exterior
    2   | 12    | max   | BD1896-1W     | insect
    3   | 18    | max   | BD1896-1W     | interior
    4   | 13    | max   | BD14120-1W    | exterior
    5   | 10    | max   | BD14120-1W    | insect
    6   | 15    | max   | BD14120-1W    | interior
    

    每个项目代码有多行。

    我在想办法 max(Height) 每个 ItemCode 其中 Type 由于某种原因,我无法完全理解该如何引用表格本身。

    我希望结果大致如下:

    Results:
    
     max(Height)| ItemCode  
    ---------------------------
     18         | BD1896-1W
     15         | BD14120-1W
    

    我该怎么做?

    2 回复  |  直到 11 年前
        1
  •  2
  •   Sirko    11 年前

    这里不需要自我引用表。

    SELECT `ItemCode`, MAX( `height` )
    FROM `MountHeights`
    WHERE `Type`= 'max'
    GROUP BY `ItemCode`
    

    Example Fiddle

        2
  •  0
  •   Girish Kumar Sinha    11 年前

    您还可以执行以下操作:

    SELECT t1.ItemCode,max(t1.height) as height
    from MountHeights as t1, test as t2 
    where t1.Type=t2.Type group by t1.Type