且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何同时对sql进行分组和排序?

更新时间:2023-11-23 23:04:10

SQLite(和MySQL)支持:

SQLite (and MySQL) support:

  SELECT t.name, 
         MAX(t.lastupdated), 
         t.status 
    FROM [table] t 
GROUP BY t.name

但是大多数其他数据库将要求您使用:

But most other databases would require you to use:

SELECT a.name, a.lastupdate, a.status
  FROM YOUR_TABLE a
  JOIN (SELECT t.name, MAX(t.lastupdated) AS max_lastupdated
          FROM YOUR_TABLE t
      GROUP BY t.name) b ON b.name = a.name
                        AND b.max_lastupdated = a.lastupdated

...但是,如果一个名称具有多个具有相同最高日期值的记录,则将返回重复项.

...though this will return duplicates if a name has more than one record with the same highest date value.