如何从同一列中获取多个最大记录?

时间:2012-08-09 08:57:34

标签: mysql group-by subquery fetch

我正在使用mysql db。

SBS => select * from docbodyversion;

 bodyid | internaldocid | versionid
--------+---------------+-----------
   1121 |          1245 |         1
   1122 |          1245 |         2
   1124 |          1246 |         1
   1125 |          1246 |         2
   1126 |          1246 |         3

我想编写这样的查询,以便o / p将是这样的 - :

 bodyid | internaldocid | versionid
--------+---------------+-----------
   1122 |          1245 |         2
   1126 |          1246 |         3

所以我只想要每个记录的最大版本ID ....

任何人都可以指导我吗?

3 个答案:

答案 0 :(得分:1)

尝试:

SELECT MAX(bodyId) AS BodyID,internaldocid, MAX(versionid) AS VersionID 
FROM docbodyversion GROUP BY internaldocid

SEE THIS FIDDLE

答案 1 :(得分:1)

试试这个:

select d.*
from docbodyversion d
join
    (select internaldocid,MAX(versionid) as versionid
     from docbodyversion
     group by internaldocid)a
on a.versionid=d.versionid
and a.internaldocid=d.internaldocid

答案 2 :(得分:0)

希望这有帮助


SELECT DISTINCT BT.BODY_ID, A.INTERNAL_DOC_ID, A.VERSION_ID
  FROM SO_BUFFER_TABLE_16 BT,
       (SELECT DISTINCT BT.INTERNAL_DOC_ID, MAX(BT.VERSION_ID) VERSION_ID
          FROM SO_BUFFER_TABLE_16 BT
         GROUP BY BT.INTERNAL_DOC_ID) A
 WHERE BT.VERSION_ID = A.VERSION_ID
   AND BT.INTERNAL_DOC_ID = A.INTERNAL_DOC_ID