我确定之前已经回答过,但我找不到它!
Customer Product
Tim Milk
Bob Milk
Customer Product Description
Tim Milk This is Tim's Milk
NULL Milk This is Anybody's Milk
我想加入表并获得以下输出(为简单起见,在示例中显示所有列):
B.Customer B.Product P.Customer P.Product P.Description
Tim MILK Tim MILK This is Tim's Milk
Bob MILK NULL MILK This is Anybody's Milk
因此,查询应首先查找是否存在特定的客户相关产品,如果是,请使用它,否则使用通用产品......
非常感谢!
答案 0 :(得分:2)
SELECT B.Customer, B.Product,
ISNULL(C.Customer,P.Customer) Customer,
CASE WHEN C.Customer IS NULL THEN P.Description
ELSE C.Description END Description
FROM B
LEFT JOIN C ON C.Product = B.Product and C.Customer = B.Customer
LEFT JOIN P ON P.Product = B.Product and P.Customer IS NULL
答案 1 :(得分:0)
我想我们需要加入两次:首先是客户和产品,然后是产品
SELECT
B.Customer,
B.Product,
IFNULL(Pfound.Customer,PnotFound.Customer) AS P_Customer,
IFNULL(Pfound.Product,PnotFound.Product) AS P_Product,
IFNULL(Pfound.Description,PnotFound.Description) AS P_Description
FROM B
LEFT JOIN P AS Pfound
ON B.Customer=Pfound.Customer
AND B.Product=Pfound.Product
LEFT JOIN P AS PnotFound
ON B.Product=PnotFound.Product
AND PnotFound.Customer IS NULL