Question

I have a SQL database with 2 tables:

Client

ClientID
ClientName
ClientBirthdate

Address

ClientID
Addressline1
Addressline2
Telephone1
Telephone2

It is possible for a client to have multiple addresses, so ClientID is not a unique value in the Address-table. My problem is that I want to send a textmessage to every unique phonenumber. Telephone1 and Telephone2 can both be empty, so basically I have no idea how many unique phonenumbers a client has. When I join them now, it looks something like this:

ClientID  | ClientName | Telephone1 | Telephone2
------------------------------------------------
Client001 | James      | 12345      | 22312
Client001 | James      | 12345      | 
Client002 | Alfred     |            | 11111
Client002 | Alfred     | 11111      | 
Client002 | Alfred     | 22222      | 

While what I want is something like this:

ClientID  | ClientName | Number1    | Number2
----------------------------------------------
Client001 | James      | 12345      | 22312
Client001 | Alfred     | 11111      | 22222

Currently I have no idea how to achieve this. Can anyone shine their light on the issue?

Thanks on beforehand,

James.

EDIT: The database already exists, and is already filled. I can't change the structure of the database, I can only do SELECT-queries.

Was it helpful?

Solution

Here is my suggested solution (if I understood the problem correctly):

SELECT DISTINCT CLIENTID, 
                CLIENTNAME, 
                TELEPHONE 
FROM   (SELECT T1.CLIENTID, 
               T1.CLIENTNAME, 
               T2.TELEPHONE1 AS Telephone 
        FROM   CLIENT T1 
               INNER JOIN (SELECT CLIENTID, 
                                  TELEPHONE1 
                           FROM   ADDRESS 
                           WHERE  TELEPHONE1 IS NOT NULL)T2 
                       ON T1.CLIENTID = T2.CLIENTID 
        UNION 
        SELECT T1.CLIENTID, 
               T1.CLIENTNAME, 
               T2.TELEPHONE2 AS Telephone 
        FROM   CLIENT T1 
               INNER JOIN (SELECT CLIENTID, 
                                  TELEPHONE2 
                           FROM   ADDRESS 
                           WHERE  TELEPHONE2 IS NOT NULL)T2 
                       ON T1.CLIENTID = T2.CLIENTID)T 

You can find a full example on SQL Fiddle.
Please let me know if you have any more question on this.

OTHER TIPS

How about

select distinct ClientID, ClientName, Number1  
  from ...  
union
select distinct ClientID, ClientName, Number2
  from ...  
  where Number2 is not null    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top