SQL计数为两个不同计数的并集

时间:2014-07-14 13:39:29

标签: sql oracle count

我有两个不同的查询,第一个会给我每天有拨出电话的用户数,第二个会给我每天有来电的用户数。我想要这两个查询的unioin。我的意思是我希望每天有来电或去电的用户数量。对此类结果的正确查询是什么?

1) select call_date, count(*) 
from 
(select distinct anum,call_date 
from  CDR 
where anum in (select msisdn from degree_cmp_week1)
)
group by call_date 
order by call_date;

2) select call_date, count(*) 
from 
(select distinct bnum,call_date 
from  CDR 
where bnum in (select msisdn from degree_cmp_week1)
)
group by call_date 
order by call_date;

FYI CDR是一个电话详细记录表。它包括anum(呼叫源),bnum(呼叫目的地)和呼叫日期。我正在寻找计算每天有任何活动(打电话给某人或某人称他/她)的人数。第一个查询将给我作为呼叫源的人数,第二个查询将给我作为呼叫目的地的人数。假设第一个查询给我n(A),第二个查询给我n(B)。我正在寻找n(A Union B)。如您所知n(A U B)= n(A)+ n(B) - n(交点B)。所以找到n(A交点B)对我也有帮助。

P.S:我使用的是oracle 11所以请考虑一下。

2 个答案:

答案 0 :(得分:0)

只需在查询中询问输入和拨出电话:

select call_date, count(num) 
from 
 (select distinct anum as num, call_date 
  from  CDR 
  where anum in (select msisdn from degree_cmp_week1)
  )
  union 
  (select distinct bnum as num ,call_date 
  from CDR
  where bnum in (select msisdn from degree_cmp_week1)
  )
group by call_date 
order by call_date;

答案 1 :(得分:0)

这样的事情可以在一个查询中提供这两个:

with ids as (
  select distinct msisdn
  from degree_cmp_week1
), calls as (
  select
    call_date,
    nvl2 (i1.msisdn, 1, 0) as a_count,
    nvl2 (i2.msisdn, 1, 0) as b_count
  from
    CDR,
    ids i1,
    ids i2
  where
    CDR.anum = i1.msisdn (+) and
    CDR.bnum = i2.msisdn (+)
)
select
  call_date, sum (a_count) as a_count,
  sum (b_count) as b_count
from calls
group by call_date
order by call_date