2013-10-13 23 views
1

我想製作一個MySql查詢在sales_flat_order表上執行。 ,並獲取已在日期之間完成第一個訂單的客戶列表。Magento MySql查詢獲取首次購買列表

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) 

感謝

回答

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'; 
+0

謝謝富蘭克林。簡單快捷 –

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

你可以嘗試這樣的事:

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