I would like to join the telephone table to the person table to display one record per person and a particular telephone number. The rule is that if the telephone has a code of MA, choose that, else if has a code of PR and Indicator="Y" choose that, if no indicator, choose the highest sequence number.
Telephone Data Example:
[tt]
ID Phone_Type Phone_Number Phone_Indic Phone_Seq
123 MA 5551212 2
123 PR 5552222 1
123 PR 5552211 3
321 PR 5559988 1
321 PR 5559987 2
444 MA 5556633 2
444 PR 5556634 Y 1
[/tt]
Result needed:
[tt]
123 MA 5551212
321 PR 5559987
444 MA 5556633
[/tt]
Full Result set
P.ID, P.Name, T.Phone_Number, P.Level, etc...
Below is part of the query I tried, but it gave error that it was returning more than one row. Hopefully there is a more efficient way to write the query. I used multiple case statements as wasn't sure how to combine into one phone number selection.
Telephone Data Example:
[tt]
ID Phone_Type Phone_Number Phone_Indic Phone_Seq
123 MA 5551212 2
123 PR 5552222 1
123 PR 5552211 3
321 PR 5559988 1
321 PR 5559987 2
444 MA 5556633 2
444 PR 5556634 Y 1
[/tt]
Result needed:
[tt]
123 MA 5551212
321 PR 5559987
444 MA 5556633
[/tt]
Full Result set
P.ID, P.Name, T.Phone_Number, P.Level, etc...
Below is part of the query I tried, but it gave error that it was returning more than one row. Hopefully there is a more efficient way to write the query. I used multiple case statements as wasn't sure how to combine into one phone number selection.
Code:
select distinct ID, Name,
Case When Phone_Type='MA' And Phone_Number_Combined is not null Then Phone_Number_Combined END MA,
Case When Phone_Type='PR' And Phone_Number_Combined is not null And Phone_Primary_Ind='Y' Then Phone_Number_Combined END PRY,
Case When Phone_Type='PR' And Phone_Number_Combined is not null Then Phone_Number_Combined END PR,
Case When Phone_Type='PR' And Phone_Number_Combined is not null Then
(
SELECT Phone_Number_Combined From Telephone T
Where Phone_Seq_Number =
(Select Max(Phone_Seq_Number)
From Telephone
Where ID = T.ID)
) PRMax,
Phone_Primary_Ind, phone_seq_number
from telephone
where Phone_Type in ('MA','PR');