2

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

 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。请参阅下面的文档编号 123。

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

我需要在报告中显示 docname 列。请问有办法解决这个问题吗?

4

2 回答 2

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的每个值的最大值。这是 ANSI 标准 SQL,大多数数据库都支持此功能。d.docnumpartition by

您的版本可能不起作用,因为计算最大值的子查询没有使用与外部查询相同的过滤条件。

于 2013-08-13T15:50:42.330 回答
0

是的,您可以选择前 1 个文档名。将您的字段选择列表替换为:

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 version 9 应显示为 Article。

于 2013-08-13T15:39:53.643 回答