我找到了一些示例,展示了如何从分组集中选择单个最旧/最新行,但是在从数据集中获取最旧的两行时遇到了麻烦。
这是我的示例表:
CREATE TABLE IF NOT EXISTS `orderTable` (
`customer_id` varchar(10) NOT NULL,
`order_id` varchar(4) NOT NULL,
`date_added` date NOT NULL,
PRIMARY KEY (`customer_id`,`order_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `orderTable` (`customer_id`, `order_id`, `date_added`) VALUES
('1234', '5A', '1997-01-22'),
('1234', '88B', '1992-05-09'),
('0487', 'F9', '2002-01-23'),
('5799', 'A12F', '2007-01-23'),
('1234', '3A', '2009-01-22'),
('3333', '7FHS', '2009-01-22'),
('0487', 'Z33', '2004-06-23'),
('3333', 'FF44', '2013-09-11'),
('3333', '44f5', '2013-09-02');
此查询返回多于两行:
SELECT customer_id, order_id, date_added
FROM orderTable T1
WHERE (
select count(*) FROM orderTable T2
where T2.order_id = T1.order_id AND T2.date_added <= T1.date_added
) <= 2;
由于我不是在寻找单行,因此这不是标准greatest-n-per-group
类型查询。
我可以为每个 customer_id 获得前两个订单,我错过了什么?