Question

I have a table as below

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

I want to know how to get a result like this

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

So the result will display only the calling numbers ( who initiate the call) and how many times theys have been called ( they occur in the "calledNumber" field ),

Was it helpful?

Solution 2

You need to start with a list of all numbers you want and then join in the ones being summarized:

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;

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top