Magento MySql查询获取首次购买者列表

时间:2013-10-13 11:37:35

标签: mysql sql magento analytics

我想生成一个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)

由于

3 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

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

答案 1 :(得分: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 
) 

答案 2 :(得分: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';