简体   繁体   中英

How could/should I write this SQL query?

I need to write an SQL query to list a customers prices for our products. We have a standard price list, customer_no = 0 , and a customer specific price list, customer_no = XXXX .

I am having trouble understanding how I can get the query to return the customer specific price for a product, if they've been given such, or if not fall back to the standard price.

To get all products and prices on the standard price list

select     prices.product_id, products.product_desc, prices.m2
from       prices, products
where      prices.product_id = products.product_id
and        prices.customer_no = 0
order by   prices.product_id asc

To get all products and prices that the customer has been specifically quoted for

select     prices.product_id, products.product_desc, prices.m2
from       prices, products
where      prices.product_id = products.product_id
and        prices.customer_no = $_SESSION['customer']
order by   prices.product_id asc

How can I perform the first query, but if the customer has their own price then replace it with that? Is this even possible?

Thanks in advance.

Steve

Edit: Sorry, missed the third line in both queries in the original post.

You have to join with the prices table twice, once for the list prices and then for the quoted prices. Use a LEFT JOIN for the latter, since some products won't have a quoted price. Then use NVL to default from the quoted price to the list price.

SELECT products.product_id, products.product_desc, NVL(p2.m2, p1.m2)
FROM products
JOIN prices p1 ON p1.product_id = products.product_id
LEFT JOIN prices p2 ON p2.product_id = products.product_id 
                    AND p2.customer_no = $_SESSION['customer']
WHERE p1.customer_no = 0

Try:

select     prices.product_id, products.product_desc, prices.m2
from       prices, products
where      prices.customer_no = nvl($_SESSION['customer'], 0)
order by   prices.product_id asc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM