假设我有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?
有什么想法吗? 提前谢谢。
答案 0 :(得分:0)
您可以在加入条件中包含日期条件,这也使联接更容易阅读,恕我直言。
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