获取组中最大值的id

时间:2014-03-06 10:38:55

标签: sql

我有一张桌子,我想收集每个组中项目的ID,列上有最大值,但我有问题。

SELECT group_id, MAX(time) 
FROM mytable
GROUP BY group_id

这样我得到了正确的行,但我需要id:

SELECT id,group_id,MAX(time)
FROM mytable
GROUP BY id,group_id

这样我得到了所有的行。我怎样才能从每个组获得最大值行的ID?

样本数据

id = 1, group_id = 1, time = 2014.01.03
id = 2, group_id = 1, time = 2014.01.04
id = 3, group_id = 2, time = 2014.01.04
id = 4, group_id = 2, time = 2014.01.02
id = 5, group_id = 3, time = 2014.01.01

从那里我应该得到id:2,3,5 谢谢!

2 个答案:

答案 0 :(得分:7)

将您的工作查询用作子查询,如下所示:

SELECT `id` 
FROM `mytable` 
WHERE (`group_id`, `time`) IN (
  SELECT `group_id`, MAX(`time`) as `time` 
  FROM `mytable`
  GROUP BY `group_id`
)

答案 1 :(得分:3)

看一下下面的演示

DROP TABLE IF EXISTS mytable;

CREATE TABLE mytable(id INT , group_id INT , time_st DATE);

INSERT INTO mytable VALUES(1, 1, '2014-01-03'),(2, 1, '2014-01-04'),(3, 2, '2014-01-04'),(4, 2, '2014-01-02'),(5, 3, '2014-01-01');

/** Check all data **/
SELECT * FROM mytable;
+------+----------+------------+
| id   | group_id | time_st    |
+------+----------+------------+
|    1 |        1 | 2014-01-03 |
|    2 |        1 | 2014-01-04 |
|    3 |        2 | 2014-01-04 |
|    4 |        2 | 2014-01-02 |
|    5 |        3 | 2014-01-01 |
+------+----------+------------+


/** Query for Actual output**/

SELECT 
    id
FROM
    mytable 
JOIN
    ( 
      SELECT group_id, MAX(time_st) as max_time 
      FROM mytable GROUP BY group_id 
    ) max_time_table 
ON mytable.group_id = max_time_table.group_id AND mytable.time_st = max_time_table.max_time;    
+------+
| id   |
+------+
|    2 |
|    3 |
|    5 |
+------+