I am joining a customer table to a phone number table based on customer_id. a customer can have many numbers, but i want only the primary one. however if there is not a primary one, i just want one of any of the others. this is what i have so far.
SELECT phon.number
FROM phones phon, customers cust
WHERE phon.customer_id (+)= cust.customer_id
AND phon.primary = 'Y';
select
case when col2 = 'Y' then col2
.....
......
end xx
from
(SELECT phon.number col1,phon.primary col2
FROM phones phon, customers cust
WHERE phon.customer_id (+)= cust.customer_id
)
select *
from customers x, phones y
where x.customer_id = y.customer_id and primary = 'Y' union
( select *
from customer x, phones y
where x.customer_id = y.customer_id and primary != 'Y'
and x.customer_id not in ( select x.customer_id
from customers x, phones y
where x.customer_id = y.customer_id and primary = 'Y')
and rownum = 1
)
I thought about DECODE. but it wont work for this situation.
"however if there is not a primary one, i just want one of any of the others ".
Outer join will bring up all the rows, What we need is to randomly pick a row ( for a customer ) for those customers
that dont have a primary phone number.
select
col1,
DECODE((decode(col2,'Y',col3,NULL)),NULL,
(SELECT PHONE_NUMBER FROM PHONES
WHERE CUSTOMER_ID = A.COL1 AND ROWNUM<=1)
,COL3) PHNO
from
(
SELECT phon.customer_id col1,phon.number col2,phone_number col3
FROM phones phon, customers cust
WHERE phon.customer_id (+)= cust.customer_id
) A
Bookmarks