当 Table2 中存在值 2 时,对 Table1 中的值 1 求和

Sum Value1 in Table 1 WHEN Value2 exists in Table2

我有2张桌子。一个 Table 包含一个 Customer_ID, Product_Code, and Price_Paid

Table 2 是具有 Product_Code 的单个列,特定于某种类型的产品。

Table1 中有数千个 product_codes,但 Table2 中只有大约 500 个。

我想编写一个查询,仅当 Product_Code 存在于 Table 2 中时,returns 我才为每个客户计算 Price_Paid 的总和。

我是否需要在子查询中执行此操作,或者是否可以在求和之前使用 CASE 语句在 Table 2 中搜索产品代码以查找 Table 1 中的匹配项。

谢谢

[T]he sum of Price_Paid per customer ONLY when the Product_Code exists in Table 2.

除非我遗漏了什么,否则这只是一个 INNER JOIN

SELECT
  Customer_ID,
  SUM(Price_Paid) AS SumOfPrice
FROM
  Table1 as t1
  INNER JOIN
  Table2 as t2
    ON t2.Product_Code = t1.Product_Code
GROUP BY 
  Customer_ID;

虽然 @Eric Brandt 的 没有问题,但它依赖于 Product_Code 在产品 table 中的独特性。更通用的解决方案是使用 EXISTS。而且我认为您可能想要按产品求和,而不仅仅是客户?

SELECT
  Customer_ID, Product_Code
  SUM(Price_Paid) AS SumOfPrice
FROM
  Table1 as t1
WHERE EXISTS (
    select 1 from Table2
    where Product_Code = t1.Product_Code
)
GROUP BY 
  Customer_ID, Product_Code;