如何选择具有最大日期的组

时间:2017-12-29 13:57:37

标签: oracle group-by max

我有这张桌子:

enter image description here

我想计算具有相同设备和最大值(DATE_RECEIPT)的WKF_NDI的数量。

我试试:

select EQUIPMENT,DATE_RECEIPT,COUNT(WKF_NDI) from CMM_DB.REF_WKF_THEMIS_H323
where date_receipt in ( select max(date_receipt)from CMM_DB.REF_WKF_THEMIS_H323)
group by EQUIPMENT, DATE_RECEIPT;

结果:

enter image description here

输出只有一行。

我希望输出如下:

PF2_SBAA-B  28/12/17 10:00:01,000000000 5
PF2_SBCC-D  27/12/17 16:50:01,000000000 5

请帮助。

3 个答案:

答案 0 :(得分:1)

您的子查询只选择最大date-receipt,因此您的主查询将只选择与该日期匹配的记录。您似乎想要为每件设备选择最长日期。

如果是这样,您需要相应地修改子查询:

select EQUIPMENT,DATE_RECEIPT,COUNT(WKF_NDI) 
from CMM_DB.REF_WKF_THEMIS_H323
where (EQUIPMENT,date_receipt) in ( select EQUIPMENT, max(date_receipt)
                                    from CMM_DB.REF_WKF_THEMIS_H323
                                    group by EQUIPMENT)
group by EQUIPMENT, DATE_RECEIPT;

答案 1 :(得分:0)

当您使用FIRST/LAST函数时,也可以在没有子查询的情况下(因此可能表现更好):

SELECT MAX(EQUIPMENT) KEEP (DENSE_RANK LAST ORDER BY DATE_RECEIPT) as EQUIPMENT, 
    MAX(DATE_RECEIPT), 
    COUNT(WKF_NDI) KEEP (DENSE_RANK LAST ORDER BY DATE_RECEIPT) 
FROM REF_WKF_THEMIS_H323
GROUP BY EQUIPMENT;

答案 2 :(得分:0)

使用over子句计算由设备分区的最大日期,将该值放在每一行上,因此它成为一个简单的where子句来选择与该日期匹配的行:

SELECT
      EQUIPMENT
    , DATE_RECEIPT
    , COUNT(WKF_NDI)
FROM (
      SELECT
            EQUIPMENT
          , DATE_RECEIPT
          , MAX(date_receipt) OVER (PARTITION BY EQUIPMENT) max_date
      FROM CMM_DB.REF_WKF_THEMIS_H323
      ) d
WHERE DATE_RECEIPT = max_date
GROUP BY
      EQUIPMENT
    , DATE_RECEIPT;