I Would like to produce a MySql
Query to be execute on sales_flat_order
table.
and to fetch a list of customers that has made their first order between dates.
select customer_id from sales_flat_order where
created_at between '1/1/2013' and '30/1/2013'
and (this is the first time that the customer has made an order.
no records for this customer before the dates)
Thanks
First, get every customer's earliest order date:
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
Results:
+-------------+-----------+--------------+---------------------+
| 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 |
+-------------+-----------+--------------+---------------------+
Note: The above assumes that the smallest entity_id
for a customer will match the earliest created_at
for a customer.
Building on this, you can join with the orders:
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';