如何在Oracle中检索上次更新的记录

时间:2013-01-21 04:36:07

标签: sql oracle

嗨,请你帮我解决这个问题,

表:Mail_Archives

 Mail_ID     Archived_by         Archived_date
   001        Sam                21/11/2011
   002        Tina               10/10/2012
   002        Tina               10/10/2012
   004        Zark               10/10/2011  

如何为此输出形成查询,我需要最近存档日期的查询结果,包括计数。例如

  Count      Archived_by     Archived_Date

   2          Tina           10/10/2012  

3 个答案:

答案 0 :(得分:0)

尝试:

select * from (
   select * from Mail_Archives order by Archived_date desc
) where rownum=1

<强>更新

select count(a.Mail_ID) top_one, b.archived_by, b.archived_date 
from Mail_Archives a, 
    (select * from (
           select * from Mail_Archives order by Archived_date desc
        ) where rownum=1
    ) b
where a.archived_by = b.archived_by 
group by b.archived_by, b.archived_date 

您可以看到它有效here

答案 1 :(得分:0)

这是一个MySQL查询,我没有Oracle来测试它,但它可能会给你一个很好的尝试。 注意:表名为'test'。 LIMIT 1将只占最高位数(显示最大计数) 表属性中的大写或小写在查询中没有区别,默认情况下,整数前的00将被截断

SELECT COUNT(mail_ID) as top_one, archived_by, archived_date
FROM test
GROUP BY mail_id
HAVING COUNT(*) = (
    SELECT COUNT(*) AS total
    FROM test
    GROUP BY mail_id
    ORDER BY total DESC
    LIMIT 1
)


top_one     archived_by     archived_date
2           Tina             2012-10-10

答案 2 :(得分:0)

尝试:

select mail_id, archived_by, archived_date, cnt
from (
select mail_id, archived_by, archived_date, count(*) cnt
from Mail_Archives
group by mail_id, archived_by, archived_date
order by archived_date desc)
where rownum = 1;

或(如果您喜欢窗口功能)

select mail_id, archived_by, archived_date, cnt from (
select mail_id, 
       archived_by, 
       archived_date, 
       row_number() over (order by archived_date desc) rn,
       count(*) over (partition by mail_id, archived_by, archived_date) cnt
from Mail_Archives)
where rn = 1;

Here is a sqlfiddle demo


更新,假设您只想要mail_id的最大日期和计数

select mail_id, archived_by, archived_date, cnt from (
select mail_id, 
       archived_by, 
       archived_date, 
       row_number() over (order by archived_date desc) rn,
       count(*) over (partition by mail_id) cnt
from Mail_Archives)
where rn = 1;

Here is a sqlfiddle demo