无法获得最大记录总数

时间:2019-05-24 10:18:34

标签: sql oracle

我无法使用Max函数获取最新记录的总数。这是我的桌子-

enter image description here

SELECT CUSTOMER, max(LAST_UPDATED) Latest_Date, SUM(TOTAL) Revenue
FROM CD_DATA
Group by CUSTOMER

这是我的预期结果,仅记录最新/最晚日期-

CUSTOMER    LATEST_DATE REVENUE
ABC        12/31/2018   1015413

这是我当前的结果在下面,其中包括所有行-

CUSTOMER    LATEST_DATE REVENUE
ABC         12/31/2018  1005126

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

select * from tablename
where LATEST_DATE= (select max(LATEST_DATE) from tablename)

答案 1 :(得分:0)

我认为这将满足您的要求

SELECT CUSTOMER, MAX(LAST_UPDATED) as Latest_Date, 
       SUM(TOTAL) KEEP (DENSE_RANK FIRST ORDER BY LAST_UPDATED DESC) as Revenue
FROM CD_DATA
GROUP BY CUSTOMER;

那是说,我对Oracle和DATE保持警惕,因为日期时间戳可以包含一个时间分量。因此,要获取最后的日期,您可能需要:

SELECT CUSTOMER, MAX(LAST_UPDATED) as Latest_Date, 
       SUM(TOTAL) KEEP (DENSE_RANK FIRST ORDER BY TRUNC(LAST_UPDATED) DESC) as Revenue
FROM CD_DATA
GROUP BY CUSTOMER;

或者:

SELECT CUSTOMER, MAX(LAST_UPDATED),
       SUM(REVENUE)
FROM (SELECT d.*,
             RANK() OVER (PARTITION BY CUSTOMER ORDER BY TRUNC(LAST_UPDATED) DESC) as seqnum
      FROM CD_DATA d
     ) d
WHERE seqnum = 1
GROUP BY CUSTOMER;