选择具有另一列的最大值的不同行

时间:2013-08-13 15:22:36

标签: sql max distinct

我正在查询文档管理数据库,其中文档可以有多个版本。因此,我的查询会因版本控制而多次返回同一文档。

 SELECT distinct d.DOCNUM, d.DOCNAME,P.FolderName
    FROM DOCUMENT as d with (nolock)
    inner join Project_T as pt on d.docnum=pt.item_id
    inner join Projects p on pt.prj_id=p.prj_id
   where d.type = 'Personal' and d.owner like '%67360'

结果:

DOCNUM     | DOCNAME     | FOLDERNAME |
-----------+----------+---------------+
123         Article        Jonathan
123         Article part1  Jonathan
256         Meeting Notes  Jonathan
5697        Memo           Jonathan

理想情况下,docnum 123应该只返回一次。

我已经加入了包含每个文档版本的表,并选择了最新版本(MAX(h.version),因此我的查询应该每行返回唯一的文档编号。

    SELECT distinct d.DOCNUM, h.version, d.DOCNAME,P.FolderName
    FROM DOCUMENT as d with (nolock)
    inner join DOCHISTORY as h on h.DOCNUM = d.docnum
    inner join Project_T as pt on d.docnum=pt.item_id
    inner join Projects p on pt.prj_id=p.prj_id
   where d.type = 'Personal' and d.owner like '%67360'
   and d.SECURITY = 'P'
   AND h.VERSION = (SELECT MAX(x.version) FROM DOCHISTORY as X 
                    where x.docnum = d.DOCNUM) 

但是这次我得到的是最新版本,但docname略有不同,它会多次返回相同的docnum。见下面的docnum 123。

DOCNUM     | Version      | DOCNAME     | FOLDERNAME |
-----------+--------------+-------------+------------+
123          9              Article        Jonathan
123          9              Article part1  Jonathan
256          1              Meeting Notes  Jonathan
5697         21             Memo           Jonathan

我需要在报告中显示docname列。请问有什么方法吗?

2 个答案:

答案 0 :(得分:0)

是的,您可以选择前1个docname。用以下内容替换您的字段选择列表:

SELECT distinct d.DOCNUM
 ,h.version 
 ,DOCNAME = (SELECT TOP 1 d2.DOCNAME FROM DOCUMENT d2, DOCHISTORY h2 
 WHERE d2.DOCNUM = d.DOCNUM and h2.DOCNUM = d.docnum)
 ,P.FolderName

....(代码的其余部分)

在上面的输出中,doc 123版本9应该显示为Article。

答案 1 :(得分:0)

使用窗口功能,您要做的事情要容易得多。这是一种方式:

select DOCNUM, version, DOCNAME, FolderName
from (SELECT d.DOCNUM, h.version, d.DOCNAME, P.FolderName,
             max(h.version) over (partition by d.docnum) as maxversion
      FROM DOCUMENT  d with (nolock)
           inner join DOCHISTORY as h on h.DOCNUM = d.docnum
           inner join Project_T as pt on d.docnum=pt.item_id
           inner join Projects p on pt.prj_id=p.prj_id
     where d.type = 'Personal' and d.owner like '%67360' and d.SECURITY = 'P'
    ) d
where version = maxversion;

表达式max(h.version) over (partition by d.docnum)是一个称为窗口函数的构造(或某些数据库中的分析函数)。为h.version的每个值返回d.docnum的最大值(基于partition by子句)。这是ANSI标准SQL,大多数数据库都支持此功能。

您的版本可能无法正常工作,因为计算最大值的子查询未使用与外部查询相同的过滤条件。