1

我想生成一个要在表MySql上执行的查询。sales_flat_order并获取在日期之间做出第一个订单的客户列表。

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)

谢谢

4

3 回答 3

2

你可以尝试这样的事情:

$collection = Mage::getModel('sales/order')->getCollection()
    ->addFieldToSelect('customer_id')
    ->addFieldToFilter('created_at', array(
        'from' => '1/1/2013',
        'to' => '30/1/2013',
    ))
    ->distinct(true);
于 2013-10-13T14:13:15.920 回答
1

也许沿着这条线。编造了一些字段名称,因此请调整您的结构。

select customer_id 
from sales_flat_order o1
where created_at between '1/1/2013' and '30/1/2013'
and Not Exist
(
    Select order_id    
    from sales_flat_order o2
    where o2.customer_id = o1.customer_id 
      And o2.order_id <> o1.order_id
      And o2.created_at < o2.created_at 
) 
于 2013-10-13T12:09:57.600 回答
1

首先,获取每个客户的最早订单日期:

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';
于 2013-10-13T21:14:50.983 回答