关系代数,找出一个数字被调用多少

时间:2014-03-27 10:54:57

标签: sql relational-algebra

我有一张表格如下

callingNumber | calledNumber 
-----------------------------
n1            | n2
n2            | n6
n9            | n3
n1            | n2
n2            | n1

我想知道如何获得这样的结果

callingNumber | calledTimes
----------------------------
n1            | 1
n2            | 2
n9            | 0

因此,结果将仅显示主叫号码(发起呼叫的人)以及他们被呼叫的次数(它们出现在"被叫号码"字段中),

2 个答案:

答案 0 :(得分:1)

Select calledNumber,COALESCE(calledTimes,0)
FROM (
      SELECT calledNumber,Count(*) as calledTimes
      FROM TableName
      GROUP BY calledNumber
     )Z
RIGHT JOIN TableName t
   ON t.callingNumber=z.calledNumber

答案 1 :(得分:0)

您需要从所需的所有数字列表开始,然后加入正在汇总的数字:

select cn.callingNumber, count(t.calledNumber) as cnt
from (select distinct callingNumber from table t) cn left outer join
     table t
     on cn.callingNumber = t.calledNumber
group by cn.callingNumber;