Selecting the latest per group of items
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Retrieving the last record in each group
我有2桌产品和成本
产品
1 2 | ProdCode - PK ProdName |
成本
1 2 3 | Effectivedate - PK RetailCOst Prodcode |
我试过这个查询:
1 2 3 4 5 | SELECT a.ProdCOde AS id, MAX(EffectiveDate) AS edate, RetailCOst AS retail FROM cost a INNER JOIN product b USING (ProdCode) WHERE EffectiveDate <= '2009-10-01' GROUP BY a.ProdCode; |
嗯,它显示了正确的有效日期,但特定有效日期的成本并不匹配。
所以我想选择每个项目匹配成本的最新日期。
例如,我选择的日期是'2009-12-25',1项的记录是这些:
1 2 3 4 | ProdCode |EffectiveDate| Cost 00010000 | 2009-01-05 | 50 00010000 | 2009-05-25 | 48 00010000 | 2010-07-01 | 40 |
所以在结果中我应该得到
希望早日收到你的消息! 谢谢!
或者,使用旧的最大连接技巧应该可以解决问题。
1 2 3 4 5 6 7 8 9 10 11 12 | SELECT p.ProdCode, SUBSTRING(MAX(CONCAT(d.EffectiveDate, c.RetailCost)), 1, 10) AS DATE, SUBSTRING(MAX(CONCAT(d.EffectiveDate, c.RetailCost)), 10, 100) + 0 AS cost FROM product p, cost c WHERE p.ProdCode = c.ProdCode AND c.EffectiveDate < '2009-10-01' GROUP BY p.ProdCode |
您需要在此处使用子查询:
1 2 3 4 5 6 7 8 | SELECT maxdates.ProdCode, maxdates.maxDate, cost.RetailCost AS retail SELECT ProdCode, MAX(EffectiveDate) AS maxDate FROM cost WHERE EffectiveDate < '2009-10-01' GROUP BY ProdCode ) maxdates LEFT JOIN cost ON (maxdates.ProdCode=cost.ProdCode AND maxdates.maxDate=cost.EffectiveDate) |
说明:
内部