选择具有唯一且最高价值的列

时间:2014-02-08 08:56:54

标签: sql oracle11g

我有两张表DOCMETAREVISIONS

CREATE TABLE "DOCMETA" 
(   
    "DID" NUMBER(*,0),  
    "XIDCPROFILE" VARCHAR2(30 CHAR),    
    "XDAMENTITY" VARCHAR2(200 CHAR)
---------------------------------------
-- some other columns
---------------------------------------
)

CREATE TABLE "REVISIONS" 
(   
    "DID" NUMBER(*,0), 
    "DDOCNAME" VARCHAR2(100 BYTE),  
    "DREVISIONID" NUMBER(*,0),  
    "DSTATUS" VARCHAR2(20 CHAR) 
---------------------------------------
-- some other columns
---------------------------------------
)

现在我想通过将这两个表合并为DOCMETA.DID=REVISIONS.DID来选择所有列

  • REVISIONS.DSTATUS的值不应为EXPIRED [查询:REVISIONS.DSTATUS NOT IN ('EXPIRED')]和
  • DOCMETA.XIDCPROFILE应具有DAMMedia, DAMVideo, DAMFile [查询:DOCMETA.XIDCPROFILE IN 'DAMMedia','DAMVideo','DAMFile')]和
  • 的值
  • DOCMETA.XDAMENTITY不是NULL且格式为WF/___/DAM [查询:DOCMETA.XDAMENTITY LIKE 'WF/___/DAM']。

以下是REVISIONS的一部分:

DID     DDOCNAME    DREVISIONID     DSTATUS
-------------------------------------------
25066   MHIS015749      92          RELEASED
25074   MHIS021584      1           RELEASED
25128   MHIS004624      5           RELEASED
25137   MHIS005679      7           RELEASED
25138   MHIS005679      8           RELEASED

我希望获得唯一REVISIONS.DDOCNAMEREVISIONS.DREVISIONID应该是最高的。从上面的数据可以看出这两行:

25137   MHIS005679  7   RELEASED
25138   MHIS005679  8   RELEASED

拥有相同的DDOCNAME所以我想在这两行中DREVISIONID获得最高行。

我很难通过将所有内容与唯一DDOCNAME和最高DREVISIONID的最后两个条件相结合来创建查询。

2 个答案:

答案 0 :(得分:0)

您可以使用以下子查询加入RESULT表:

SELECT DID, DDOCNAME, MAX(DREVISIONID) AS LASTREVISIONID
  FROM REVISIONS
 GROUP BY DID, DDOCNAME

最终查询如下:

SELECT D.DID, R.DDOCNAME, R.REVISIONID, R.DSTATUS
  FROM DOCMETA D INNER JOIN 
       REVISIONS R ON D.DID = R.DID INNER JOIN
       (SELECT DID, DDOCNAME, MAX(DREVISIONID) AS LASTREVISIONID
          FROM REVISIONS
         GROUP BY DID, DDOCNAME) R2 ON R.DID=R2.DID
                                   AND R.DDOCNAME=R2.DDOCNAME
                                   AND r.REVISIONID=R2.LASTREVISIONID
 WHERE D.DSTATUS <> 'EXPIRED'
   AND XIDCPROFILE IN ('DAMMedia','DAMVideo','DAMFile')
   AND XDAMENTITY LIKE 'WF/%/DAM'

答案 1 :(得分:0)

SELECT *

FROM REVISIONS R

INNER JOIN DOCMETA D

ON R.DID=R.DID

AND R.DREVISIONID=

  (SELECT MAX(DREVISIONID) FROM REVISIONS b WHERE R.DDOCNAME=b.DDOCNAME

  )

您可以将此代码片段与查询的其余部分合并。