如何创建唯一数字和频率的总和

时间:2019-07-09 18:14:53

标签: sql

使用SQL,我希望得到一个报告,该报告显示给定的LinkedUserMailboxName收到了多少个唯一调用以及总共收到了多少个调用。我无法在查询中为“唯一数字”创建总和。请帮忙。

select count(*), UMADUserAccounts.Country as 'Country',
UMADUserAccounts.RankLevel as 'Level',
LinkedUserMailboxName,
CallingNumber as 'Unique Numbers',
count(callingnumber) as 'How many times' 
from UMCallDataRecord 
inner join UMADUserAccounts on 
UMCallDataRecord.LinkedUserMailboxName = UMADUserAccounts.EmailAddress  where 
CallType = 'callansweringvoicemessage' 
and 
[date] between '2019-05-01' and '2019-05-31' 
group by UMADUserAccounts.Country,
UMADUserAccounts.abcRankLevel,
LinkedUserMailboxName,
CallingNumber 
order by 
UMADUserAccounts.Country asc


Expected Output
Country Level LinkedUserMailboxName   Unique Numbers   How many times
USA Associate   Alexia.b@ca.abc.com         2               2
USA Associate   Angelina.asas@de.abc.com    2               2
USA Associate   Asad.slob@ca.abc.com        2               2
USA Associate   Austin.jones@ca.abc.com     3               3
USA Associate   Bankole.smith@ca.abc.com    3               13


Output
Country Level   LinkedUserMailboxName      Unique Numbers   How many times
USA Associate   Alexia.b@ca.abc.com         +11232561600            1
USA Associate   Alexia.b@ca.abc.com         +11235712476            1
USA Associate   Angelina.asas@de.abc.com    +49132433113287         1
USA Associate   Angelina.asas@de.abc.com    daniel.boy@abc.com      1
USA Associate   Asad.slob@ca.abc.com        +11255722196            1
USA Associate   Asad.slob@ca.abc.com        terry.q.public@abc.com  1
USA Associate   Austin.jones@ca.abc.com     +11239840743            1
USA Associate   Austin.jones@ca.abc.com     +11239543735            1
USA Associate   Austin.jones@ca.abc.com     +11234325015            1
USA Associate   Bankole.smith@ca.abc.com    +112355810290           1
USA Associate   Bankole.smith@ca.abc.com    +11233508936            1
USA Associate   Bankole.smith@ca.abc.com    +11237477000            11

1 个答案:

答案 0 :(得分:1)

我认为您想要count(distinct)

select count(*), ua.Country as Country, ua.RankLevel as Level,
       LinkedUserMailboxName,
       count(distinct CallingNumber) as Unique_Numbers,
       count(*) as how_many_times
from UMCallDataRecord cdr inner join
     UMADUserAccounts ua
     on cdr.LinkedUserMailboxName = ua.EmailAddress 
where cdr.CallType = 'callansweringvoicemessage' and
      cdr.[date] >= '2019-05-01' and 
      cdr.[date] < '2019-06-01'
group by ua.Country, ua.abcRankLevel, LinkedUserMailboxName,
order by ua.Country asc;

注意:

  • 表别名使查询更易于编写和阅读。
  • 限定所有列引用,特别是当查询引用多个表时。
  • 我删除了between用于日期比较。亚伦·伯特兰德(Aaron Bertrand)很好explanation解释为什么在这种情况下应避免使用between