Sunday, April 11, 2010

Customer Accounts that have Non Primary Phone Contact Points only

I was asked to provide a list of customer accounts that have
1. No primary phones associated with the account
2. Have non-primary phone associated with the account

So I translated the given requirement into sql query as given below


SELECT account_number
FROM hz_cust_accounts hca
WHERE NOT EXISTS ( SELECT 1
FROM hz_contact_points hcp
WHERE contact_point_type = 'PHONE'
AND owner_table_name = 'HZ_PARTIES'
AND owner_table_id = hca.party_id
AND primary_flag = 'Y'
)
AND EXISTS ( SELECT 1
FROM hz_contact_points hcp
WHERE contact_point_type = 'PHONE'
AND owner_table_name = 'HZ_PARTIES'
AND owner_table_id = hca.party_id
AND NVL(primary_flag,'N') = 'N'
)

This query was very slow. There were not too many customer accounts that met the above condition. I thought about it and used the following query. It was much better.

SELECT /*+ use_nl ( phone ca) */
account_number
FROM hz_cust_accounts ca
, (SELECT owner_table_id
FROM ( SELECT owner_table_id
, SUM(DECODE(primary_flag,'Y',1,0)) primary_count
, SUM(DECODE(primary_flag,'Y',0,1)) non_primary_count
FROM hz_contact_points
WHERE status = 'A'
AND contact_point_type = 'PHONE'
AND owner_table_name = 'HZ_PARTIES'
GROUP BY owner_table_id
)
WHERE primary_count = 0 AND non_primary_count > 0
) phone
WHERE ca.party_id = phone.owner_table_id



I think this query can give better information about objects that have only non-primary phones

SELECT owner_table_name, owner_table_id
FROM ( SELECT owner_table_name, owner_table_id
, SUM(DECODE(primary_flag,'Y',1,0)) primary_count
, SUM(DECODE(primary_flag,'Y',0,1)) non_primary_count
FROM apps.hz_contact_points
WHERE status = 'A'
AND contact_point_type= 'PHONE'
GROUP BY owner_table_name, owner_table_id
)
WHERE primary_count = 0 AND non_primary_count > 0

No comments:

Post a Comment