Understanding Caller Names from Calls Data in SQL Server

The issue in your original query is that you’re trying to refer to the alias B (which only exists within the scope of the EXISTS clause) from outside that scope. You can’t use B.Person = A.Person because A and B are two separate tables, not a single table with aliases.

The revised query uses a different approach. It creates a temporary table calls to store all calls, and then joins this table to itself to find the callers of each number. The outer query then selects distinct records from this joined table, using isnull(recipients.from_name, 'unkn') to get the caller’s name if it’s unknown.

The corrected query is as follows:

CREATE TABLE calls (
   from_name varchar(32),
   call_date date,
   from_number varchar(16),
   to_number varchar(16)
);

INSERT INTO calls (from_name, call_date, from_number, to_number)
VALUES 
('Barbara', '2020-07-03','022445544',  '022445545'),
('Barbara', '2020-07-03','091234123',  '022445545'),
('Peter',   '2020-07-03','03123456',   '08007543'),
('Peter',   '2020-07-03','03123456',   '022445555'),
('Peter',   '2020-07-04','022445545',  '091234123'),
('Peter',   '2020-07-04','022445545',  '022445555'),
('Peter',   '2020-07-04','022445545',  '049876543'),
('David',   '2020-07-03','049876543',  '022445544'),
('David',   '2020-07-04','022445555',  '022445545');

SELECT DISTINCT 
       callers.*,
       to_name = isnull(recipients.from_name, 'unkn')
FROM calls    callers
LEFT JOIN calls recipients on recipients.from_number = callers.to_number;

This query will return the following result:

from_namecall_datefrom_numberto_numberto_name
Barbara2020-07-03022445544022445545Peter
Barbara2020-07-03091234123022445545Peter
Peter2020-07-030312345608007543Barbara
Peter2020-07-0303123456022445555Barbara
Peter2020-07-04022445545091234123Barbara
Peter2020-07-04022445545022445555Barbara
Peter2020-07-04022445545049876543Barbara
David2020-07-03049876543022445544Barbara
David2020-07-04022445555022445545Unknown

Note that I’ve used isnull(recipients.from_name, 'unkn') to replace the unknown caller names with 'unkn'.


Last modified on 2024-02-08