【问题标题】:Left Join with condition from join左连接条件来自连接
【发布时间】:2013-05-14 03:39:47
【问题描述】:

假设我有 2 张桌子:

    Table_1 has |Product_ID|Max_Date
    Table_2 has |Invoice_ID|Product_ID|Sale_Date|Amount_Sold

Table_2 存储产品的所有销售额。

我想以这样一种方式加入表格,即我从 Table_2 中获得按 Product_ID 分组的 SUM(Amount_Sold),但只考虑 Table_1 中每个产品在 Max_Date 之前发生的销售额。

我试过了

SELECT * FROM 
(SELECT * FROM Table_1)a 
LEFT JOIN 
(SELECT Product_ID,Sale_Date,SUM(Amount_Sold) FROM Table_2 GROUP BY Product_ID)b
ON a.Product_ID=b.Product_ID AND b.Sale_Date<a.Max_Date

但它没有返回正确的总和。

我认为答案可能是这样的,但我一直无法弄清楚...... mysql: How to INNER JOIN a table but limit join to 1 result with the highest vote or count?

有什么想法吗? 提前致谢。

【问题讨论】:

    标签: mysql left-join


    【解决方案1】:

    您可以在连接条件中包含日期条件,这也使连接更易于阅读,恕我直言。

    SELECT t2.product_id, sum(amount_sold)
        FROM Table_1 t1 INNER JOIN Table_2 t2
        ON t1.product_id = t2.product_id AND t2.sale_date <= t1.max_date
        GROUP BY t2.product_id
    

    【讨论】:

      猜你喜欢
      • 2011-12-11
      • 2013-08-23
      • 2015-07-18
      • 2015-05-13
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 2012-02-27
      • 2013-01-19
      相关资源
      最近更新 更多