首先,获取每个客户的最早订单日期:
SELECT
customer_id,
MIN(entity_id) AS entity_id,
MIN(increment_id) AS increment_id,
MIN(created_at) AS created_at
FROM sales_flat_order
GROUP BY customer_id
结果:
+-------------+-----------+--------------+---------------------+
| customer_id | entity_id | increment_id | created_at |
+-------------+-----------+--------------+---------------------+
| 1 | 1 | 100000001 | 2012-04-27 22:43:27 |
| 2 | 15 | 100000015 | 2012-05-10 14:43:27 |
+-------------+-----------+--------------+---------------------+
注意:以上假设客户的最小entity_id
将与客户的最早匹配created_at
。
在此基础上,您可以加入订单:
SELECT o.* FROM sales_flat_order AS o
JOIN (
SELECT
customer_id,
MIN(entity_id) AS entity_id,
MIN(created_at) AS created_at
FROM sales_flat_order
GROUP BY customer_id
) AS first ON first.entity_id = o.entity_id
WHERE
first.created_at BETWEEN '2013-01-01' AND '2013-01-30';