Looking for some directions on what options I should be considering for the following problem of creating a select statement (SQL SERVER) based on conditions:
NOTE: simplifying the actual problem
If I have two tables, each with a field I need to use
EXAMPLE:
CUSTOMER.CUSTOMER_ID
PRODUCT.PRODUCT_ID
I have 2 other tables that hold special product pricing based on these two fields
EXAMPLE:
CUSTOMER_PRICING
***************************************
* CUSTOMER_ID * PRODUCT_ID * PRICE *
* *
* ABC * 100 * 5.00 *
***************************************
MARKET_PRICING
***************************************
* CUSTOMER_ID * PRODUCT_ID * PRICE *
* *
* ACME * 200 * 7.00 *
***************************************
For every CUSTOMER.CUSTOMER_ID and PRODUCT.PRODUCT_ID I want to join CUSTOMER_PRICING and MARKET_PRICING records using a left outer join. But the conditions are only if
A) the PRICE field is not null
B) and if a CUSTOMER_ID/PRODUCT_ID exists in both, I only want the record from CUSTOMER_PRICE
Something like:
IF EXISTS (SELECT C.CUSTOMER_ID, P.PRODUCT_ID FROM CUSTOMER C, PRODUCT P
WHERE C.CUSTOMER_ID, P.PRODUCT_ID IN
(SELECT PRICE FROM CUSTOMER_PRICE WHERE PRICE IS NOT NULL))
ELSE IF EXISTS
(SELECT C.CUSTOMER_ID, P.PRODUCT_ID FROM CUSTOMER C, PRODUCT P
WHERE C.CUSTOMER_ID, P.PRODUCT_ID IN
(SELECT PRICE FROM MARKET_PRICE WHERE PRICE IS NOT NULL))
***then somehow do a join on these results…..
Any Suggestions?
Creating a view called CMPricing would greatly simplify this situation.
Then you query this view to get what you want.
This view will contain only the data that is common between both “PRICE” tables where both “PRICE” values are not null. This view in essence does the filtering for you which in turn makes your queries with the other data tables easier to do and understand.