根据部门选择具有最大日期的不同ID

时间:2018-05-02 07:04:00

标签: sql oracle greatest-n-per-group

我有一个如下表

RevNo | RevContent          | PIC      | Created
-------------------------------------------------------
 00   | Testing Purpose     | Smith   | 2008-01-11
 01   | Testing Purpose     | Windsor | 2008-02-01
 02   | Test                | Thorn   | 2008-01-05
 02   | Testing             | Baker   | 2008-03-01
 03   | Testing only        | Sykes   | 2008-01-20

我想要输出如下,它显示每个rev no的最新日期。和其他细节

RevNo | RevContent          | PIC      | Created
----------------------------------------------------
 00   | Testing Purpose     | Windsor | 2008-02-11
 01   | Testing             | Baker   | 2008-03-01
 02   | Testing only        | Sykes   | 2008-01-20

但是当我运行sql时,它只显示最新日期的值,如下所示,我希望它显示每个rev no的最新日期。它基于部门(会议)。

RevNo | RevContent          | PIC      | Created
----------------------------------------------------
 01   | Testing             | Baker   | 2008-03-01

我的查询:

SELECT CCSMASTERLISTREVNO, CCSREVCONTENT, CCSPREPAREDREV, CCSREVEFFECTIVEDATE
FROM CCS2_TBL_MASTERLIST a 
WHERE CCSEQUIPMENTDPMT = :DPMT AND CCSREVEFFECTIVEDATE = 
 (
SELECT MAX(CCSREVEFFECTIVEDATE) FROM CCS2_TBL_MASTERLIST 
 GROUP BY CCSMASTERLISTREVNO HAVING CCSMASTERLISTREVNO =a.CCSMASTERLISTREVNO
  ) 
ORDER BY CCSMASTERLISTREVNO DESC

3 个答案:

答案 0 :(得分:0)

每个部门(CCSMASTERLISTREVNO)的子查询组,但HAVING子句是错误的。相反,您应该在IN子句中使用复合列。像这样:

SELECT CCSMASTERLISTREVNO
       , CCSREVCONTENT
       , CCSPREPAREDREV
       , CCSREVEFFECTIVEDATE
FROM CCS2_TBL_MASTERLIST a 
WHERE CCSEQUIPMENTDPMT = :DPMT 
AND (CCSMASTERLISTREVNO, CCSREVEFFECTIVEDATE) in 
 (
     SELECT CCSMASTERLISTREVNO, MAX(CCSREVEFFECTIVEDATE) 
     FROM CCS2_TBL_MASTERLIST 
     GROUP BY CCSMASTERLISTREVNO )
  ) 
ORDER BY CCSMASTERLISTREVNO DESC 

答案 1 :(得分:0)

一种选择是使用row_number()

SELECT RevNo
    ,RevContent
    ,PIC
    ,Created
FROM (
    SELECT t.*
        ,row_number() OVER (
            PARTITION BY RevNo ORDER BY Created DESC
            ) AS rn
    FROM t
    )
WHERE rn = 1;

另一种方法是使用LAST聚合函数。

SELECT RevNo
    ,MAX(RevContent) KEEP ( DENSE_RANK LAST ORDER BY CREATED ) as RevContent
    ,MAX(PIC) KEEP ( DENSE_RANK LAST ORDER BY CREATED ) as PIC
    ,MAX(Created) as CREATED
FROM t
GROUP BY RevNo;

答案 2 :(得分:-1)

我没有真正理解你的问题,但也许这可以帮到你。

SELECT RevNo, RevContent, PIC, MAX(Created) as Created
FROM your_table_name 
GROUP BY RevNo
ORDER BY Created DESC

我认为您首先需要按照RevNo对条目进行分组,然后按照每个组的最后创建进行排序。