如何返回具有最大值的多行

时间:2014-07-16 13:30:06

标签: mysql select max

我目前正在做一个文档管理系统,我遇到了一些问题。我希望能够选择并显示具有最高版本号的每个唯一文档 这是我目前的代码:

SELECT DISTINCT( policyheader.policytitle ), 
               Max(policyrecords.policyversion)    AS maxPolicy, 
               policyrecords.useruploaddate, 
               policyrecords.policydesc, 
               LEFT(policyrecords.whatchanged, 30) AS changes, 
               policyheader.policyref 
FROM   policyrecords 
       INNER JOIN policyheader 
               ON policyrecords.policyref = policyheader.policyref 
GROUP  BY policyrecords.policydesc, 
          policyrecords.policyversion 

我也一直在尝试IN。它正在返回这些数据:

enter image description here

我希望它返回的是这些数据:

enter image description here

3 个答案:

答案 0 :(得分:0)

您可以通过多种方式解决此问题。 not exists方法通常表现良好:

SELECT ph.policyTitle, pr.*
FROM policyrecords pr INNER JOIN
     policyheader ph
     ON pr.policyRef = ph.policyRef
WHERE not exists (select 1
                  from policyrecords pr2
                  where pr2.policyRef = pr.policyRef and
                        pr2.policyVersion > pr.policyVersion
                 );

这实现了以下逻辑:"从policyrecords获取所有记录,其中没有相同policyRef和更大policyVersion的记录。"这是一种说法,让我获得最大版本。

答案 1 :(得分:-1)

尝试此查询

SELECT
    DISTINCT(policyheader.policyTitle),
    MAX(policyrecords.policyVersion) AS maxPolicy,
    policyrecords.userUploadDate,
    policyrecords.policyDesc,
    left(policyrecords.whatChanged,30) as changes,
    policyheader.policyRef
FROM policyrecords
    INNER JOIN policyheader ON policyrecords.policyRef = policyheader.policyRef
GROUP BY
    DISTINCT(policyheader.policyTitle)

如果按版本分组,您将看到一个policyTitle的所有版本:)

答案 2 :(得分:-2)

SELECT
 policyheader.policyTitle,
 policyrecords.policyVersion,
 policyrecords.userUploadDate,
 policyrecords.policyDesc,
 left(policyrecords.whatChanged,30) as changes,
 policyheader.policyRef
 FROM policyrecords
 INNER JOIN policyheader ON policyrecords.policyRef = policyheader.policyRef
 GROUP BY
 policyrecords.policy
 order by policyrecords.policyVersion desc