SQL选择列值与不同表中的列值匹配的行

时间:2015-04-05 15:11:09

标签: sql sas enterprise-guide

我的表A包含列' CustomerID'和' MONTH'以及专栏' PRODUCT'这总是相同的,例如产品X

我还有表B,其中包含列' CustomerID'和' MONTH'但是这张表包含了很多产品,而不仅仅是X.

我正在尝试从表B(许多产品)中选择其客户ID'和' MONTH'匹配表A中的一行,以便我最终得到客户在购买的同一个月内购买的产品产品X

我尝试了以下内容:

PROC SQL;
   CREATE TABLE DATA.RESULT AS
   SELECT LOTS.Customer_ID, 
          LOTS.Product_Name, 
          LOTS.Order_Revenue, 
          LOTS.Month_Ordered
   FROM DATA.Family_Holiday_Orders_Plus AS LOTS
   INNER JOIN DATA.X AS X1 ON (X1.Customer_ID = LOTS.Customer_ID)
   INNER JOIN DATA.X AS X2 ON (X2.Month_Ordered = LOTS.Month_Ordered);
QUIT;

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望从LOTS中选择DATA.X中具有相同Customer_IDMonth_Ordered的另一行的所有产品 价值存在。

SELECT LOTS.Customer_ID, 
       LOTS.Product_Name, 
       LOTS.Order_Revenue, 
       LOTS.Month_Ordered
FROM DATA.Family_Holiday_Orders_Plus AS LOTS
WHERE EXISTS (
    SELECT 1 FROM DATA.X AS X1 WHERE X1.Customer_ID = LOTS.Customer_ID
    AND X1.Month_Ordered = LOTS.Month_Ordered
)