zoukankan      html  css  js  c++  java
  • SQL

    有时需要以某一字段作为分组,筛选每一组的另一字段值最大(或最小)的记录。例如,有如下表 app,存储了 app 的 ID、名称、版本号等信息。现在要筛选出每个 app 版本最大的记录。

    方法一

    SELECT a.* FROM app a 
    WHERE a.app_version = (SELECT MAX(b.app_version) FROM app b WHERE b.app_name = a.app_name) 
    ORDER BY a.app_name;

    方法二

    SELECT a.* FROM app a
    WHERE NOT EXISTS(SELECT 1 FROM app b WHERE b.app_name = a.app_name AND b.app_version > a.app_version)
    ORDER BY a.app_name;

    方法三

    SELECT a.* 
    FROM app a, (SELECT app_name, MAX(app_version) AS app_version FROM app GROUP BY app_name) b
    WHERE a.app_name = b.app_name
    AND a.app_version = b.app_version
    ORDER BY a.app_name;

    方法四

    SELECT a.* 
    FROM app a INNER JOIN (SELECT app_name, MAX(app_version) AS app_version FROM app GROUP BY app_name) b
    ON a.app_name = b.app_name
    AND a.app_version = b.app_version
    ORDER BY a.app_name;
  • 相关阅读:
    a==null和a.equals("null")的区别
    PHP_EOL换行符
    mysql 重启
    异或的用法
    so easy(并查集+unordered_map)
    牛客练习赛51 C 勾股定理
    Period II
    Simpsons’ Hidden Talents
    POJ-1961 Period
    poj-2406 Power Strings
  • 原文地址:https://www.cnblogs.com/huey/p/6145662.html
Copyright © 2011-2022 走看看