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

时间:2011-05-31 02:50:15

标签: sql sqlite greatest-n-per-group

我有以下sqlite3表:

Name | LastUpdated | Status
============================
Adam | 2011-05-28  | 1
Bob  | 2011-05-05  | 6
Adam | 2011-05-27  | 2
Adam | 2011-05-16  | 1
Adam | 2011-05-26  | 3
Bob  | 2011-05-18  | 1
Adam | 2011-05-29  | 6

我希望选择LastUpdated列排序的每个Name的一行。所以我想得到这些数据:

Adam | 2011-05-29  | 6
Bob  | 2011-05-18  | 1

我想我必须做一个子查询,但我无法弄清楚如何去做。

3 个答案:

答案 0 :(得分:3)

SQLite(和MySQL)支持:

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

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

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

...如果名称包含多个具有相同最高日期值的记录,则会返回重复项。

答案 1 :(得分:1)

您可以将其作为自我加入。在这种情况下,我调用了表“table”,用你自己的表名替换:

SELECT
  test.Name,
  test.LastUpdated,
  test.Status
FROM
  test INNER JOIN 
    ( SELECT
        Name,
        MAX(LastUpdated) AS LatestUpdated
      FROM
        test
      GROUP BY
        Name ) AS latest
    ON test.Name = latest.name AND test.LastUpdated = latest.LatestUpdated;

希望这有帮助!

答案 2 :(得分:0)


SELECT 
       t.Name, 
       (Select LastUpdated from [table] t1 where t.name = t1.name order by lastUpdated desc LIMIT 1) as LastUpdated, 
       (Select Status from [table] where t1.name = t.name order by lastUpdated desc LIMIT 1) as Status
FROM [table] t
GROUP by Name