从Oracle中的每个组中查找最大值

时间:2020-09-28 17:45:36

标签: sql oracle

我有以下情况: 输入数据:

 ---------------------------------------------------------------
| ID    | Account   | Sub_Acct  | Email                         |
 ---------------------------------------------------------------
| 100   | AD        | AD1       | 123@xyz.com                   |
| 100   | AB        | AB1       | test@abc.com, 123@xyz.com     |
| 100   | AB        | AB2       | test@abc.com, 123@xyz.com     |
| 200   | CD        | CD1       | test.1@pqr.com, 123@abc.com   |
| 200   | AB        | AB1       | test.2@pqr.com                |
| 200   | CD        | CD2       | test.1@pqr.com, 123@abc.com   |
| 200   | AB        | AB2       | 123@abc.com                   |
| 200   | CD        | CD3       | test.1@pqr.com, 123@abc.com   |
 ---------------------------------------------------------------

我需要计算按ID划分的各个帐户。无论哪个帐户的计数最高,我都希望显示具有单独条目的相应帐户,并且将Sub_acct列填充为NULL。其余所有其他帐户应使用该特定ID内各自的Sub_acct值填充。

要从“电子邮件”列中提取的电子邮件域。辅助帐户的email_domain列值(在特定ID中)将具有主要帐户的值(即最大数量)。以下是预期的输出:

 ------- -------------------------------------------
| ID    | Account   | Sub_Acct  | Email_Domain      |
 ------- -------------------------------------------
| 100   | AB        |           | abc.com, xyz.com  |   
| 100   | AD        | AD1       | abc.com, xyz.com  |
| 200   | CD        |           | pqr.com, abc.com  |
| 200   | AB        | AB1       | pqr.com, abc.com  |
| 200   | AB        | AB2       | pqr.com, abc.com  |
 ---------------------------------------------------

我已经编辑了这个问题。对不起造成的麻烦。 有人可以帮助Oracle中的sql查询吗?预先感谢。

2 个答案:

答案 0 :(得分:2)

这适用于Oracle 10 ...

    with rank1 as
    (
        select id, 
        account, 
        email, count(account) as account_count, 
        rank() over (partition by id order by count(account) desc) as order_rank
        from table1
        group by id, account, email
    )
    select t1.*, 
    r1.account as primary_account, 
    r1.email as primary_email
    from table1 t1
    join rank1 r1
      on r1.id = t1.id
    where r1.order_rank = 1

答案 1 :(得分:0)

在表中,一个ID /帐户对可以出现多次。在您的示例中,这样的一对始终具有相同的电子邮件。这样可以保证吗?如果是这样,则您的表将不被规范化,将来您可能会遇到一致性问题。

但是,依靠它可以使查询的编写变得容易:

select
  t.id,
  t.account,
  t.email,
  s.primary_account,
  s.primary_email
from mytable
join
(
  select
    id,
    stats_mode(account) as primary_account,
    stats_mode(email) as primary_email
  from mytable
  group by id
) s on s.id = t.id
order by id, account;

(这将更加容易,受Oracle STATS_MODE OVER支持,但现在还没有。)