给定一个表(daily_sales),其中包含以下数据/列的10万行:
id rep sales date 1 a 123 12/15/2011 2 b 153 12/15/2011 3 a 11 12/14/2011 4 a 300 12/13/2011 5 a 120 12/12/2011 6 b 161 11/15/2011 7 a 3 11/14/2011 8 c 13 11/14/2011 9 c 44 11/13/2011
编写报告(使用SQL完整显示所有名称的两个最新条目(代表,销售,日期))的最有效方法是什么,因此输出将是:
a 123 12/15/2011 a 11 12/14/2011 b 153 12/15/2011 b 161 11/15/2011 c 13 11/14/2011 c 44 11/13/2011
谢谢!
对于MySQL,在 @Quassnoi的博客 中进行了解释,该索引是(name, date)使用和使用的:
(name, date)
SELECT t.* FROM ( SELECT name, COALESCE( ( SELECT date FROM tableX ti WHERE ti.name = dto.name ORDER BY ti.name, ti.date DESC LIMIT 1 OFFSET 1 --- this is set to 2-1 ), CAST('1000-01-01' AS DATE)) AS mdate FROM ( SELECT DISTINCT name FROM tableX dt ) dto ) tg , tableX t WHERE t.name >= tg.name AND t.name <= tg.name AND t.date >= tg.mdate