-2

嗨,你能帮我解决这个问题吗?

表: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  
4

3 回答 3

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 

你可以看到它在这里工作

于 2013-01-21T04:41:10.550 回答
0

这是一个 MySQL 查询,我没有 Oracle 来测试它,但它可能会给你一个很好的尝试。注意:表名称为“测试”。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
于 2013-01-21T05:17:53.147 回答
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;

这是一个 sqlfiddle 演示


更新假设您只需要 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;

这是一个 sqlfiddle 演示

于 2013-01-21T06:17:07.477 回答