【发布时间】: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?
有什么想法吗? 提前致谢。
【问题讨论】: