表和数据:
CREATE TABLE test1 (pid INT,id INT,LEVEL INT);insert  into `test1`(`pid`,`id`,`level`) 
values 
(1228582896,1306,10),
(1228582896,1307,21),
(1228582896,1308,40),
(1228582897,1303,10),
(1228582897,1304,21),
(1228582897,1305,40),
(1228582898,1299,10),
(1228582898,1300,20),
(1228582898,1301,40),
(1228582901,1315,10),
(1228582901,1316,21),
(1228582901,1317,40),
(1228582902,1312,10),
(1228582902,1313,20),
(1228582902,1314,40),
(1228582903,1309,10),
(1228582903,1310,20),
(1228582903,1311,40);我想得到以下的结果,每个PID最大的level,如下:
pid id level
1228582896 1308 40
1228582897 1305 40
1228582898 1301 40
1228582901 1317 40
1228582902 1314 40
1228582903 1311 40请指教,谢谢。
我是这样写得,但是ID不对。
SELECT pid,id, MAX(LEVEL) FROM test1 GROUP BY pid
求教。

解决方案 »

  1.   

    select * from test1 a where not exists(select 1 from test1 where pid=a.pid and level>a.level);orselect a.* from test1 a left join test1 b on a.pid=b.pid and b.level>a.level group by a.pid,a.id,a.level
    having count(b.pid)=0;
      

  2.   

    mysql> SELECT pid,max(id), MAX(LEVEL) FROM test1 GROUP BY pid;
    +------------+---------+------------+
    | pid        | max(id) | MAX(LEVEL) |
    +------------+---------+------------+
    | 1228582896 |    1308 |         40 |
    | 1228582897 |    1305 |         40 |
    | 1228582898 |    1301 |         40 |
    | 1228582901 |    1317 |         40 |
    | 1228582902 |    1314 |         40 |
    | 1228582903 |    1311 |         40 |
    +------------+---------+------------+
    6 rows in set (0.00 sec)
      

  3.   

    select a.pid, a.id, b.max_level
    from test1 a, (select pid, max(a.level) as max_level from test1 a where a.pid = pid group by a.pid) b
    where a.pid = b.pid and a.level = b.max_level
      

  4.   

    SELECT * FROM test1 a WHERE NOT EXISTS(SELECT 1 FROM test1 WHERE pid=a.pid AND LEVEL>a.LEVEL)
      

  5.   

    参考下贴中的方法,及N=1时的特例。http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
    分组取最大N条记录方法征集
      

  6.   

    谢谢,根据提示已经找到答案。SELECT * FROM (
    SELECT * FROM test1 ORDER BY pid,LEVEL DESC ) AS t
    GROUP BY pid先排序,再分组。