0

我敢肯定这个问题之前已经回答过,但我找不到!

表 - 预订 B

Customer    Product
Tim         Milk
Bob         Milk

表 - 产品 P

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

所以,查询应该首先查找是否有特定的客户相关产品,如果有,使用它,否则使用通用产品......

非常感激!

4

2 回答 2

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
于 2012-09-19T12:45:35.170 回答
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
于 2012-09-19T12:40:00.417 回答