這裏有一個查詢返回的最新差距,以天爲單位,爲每一位客戶,使用JOIN:
SELECT e1.customer_email, DATEDIFF(e1.created_at, e2.created_at) AS gap
FROM eshop_flat_sales_order e1
LEFT JOIN eshop_flat_sales_order e2
ON e2.customer_email = e1.customer_email
AND e2.created_at < e1.created_at
LEFT JOIN eshop_flat_sales_order e3
ON e3.customer_email = e1.customer_email
AND e3.created_at < e2.created_at
WHERE e3.customer_email IS NULL
ORDER BY e1.customer_email
這個查詢假設created_at
是DATE
場。
它將返回NULL
對於gap
其中一個客戶只有一個訂單。如果您不想僅向一個訂單返回結果,請將第一個連接從LEFT JOIN
更改爲JOIN
。
這裏的另一個版本,只考慮complete
訂單:
SELECT e1.customer_email, DATEDIFF(e1.created_at, e2.created_at) AS gap
FROM eshop_flat_sales_order e1
LEFT JOIN eshop_flat_sales_order e2
ON e2.customer_email = e1.customer_email
AND e2.created_at < e1.created_at
AND e2.status = 'complete'
LEFT JOIN eshop_flat_sales_order e3
ON e3.customer_email = e1.customer_email
AND e3.created_at < e2.created_at
AND e3.status = 'complete'
WHERE e1.status = 'complete'
AND e3.customer_email IS NULL
ORDER BY e1.customer_email
這將顯示所有所有相應的訂單之間的差距,爲所有的客戶:
SELECT e1.customer_email, DATEDIFF(e1.created_at, e2.created_at) AS gap
FROM eshop_flat_sales_order e1
JOIN eshop_flat_sales_order e2
ON e2.customer_email = e1.customer_email
AND e2.created_at < e1.created_at
AND e2.status = 'complete'
LEFT JOIN eshop_flat_sales_order e3
ON e3.customer_email = e1.customer_email
AND e3.created_at < e1.created_at
AND e3.created_at > e2.created_at
AND e3.status = 'complete'
WHERE e1.status = 'complete'
AND e3.customer_email IS NULL
ORDER BY e1.customer_email ASC, e1.created_at DESC
這將顯示的平均差距對於每位顧客:
SELECT e1.customer_email, AVG(DATEDIFF(e1.created_at, e2.created_at)) AS gap
FROM eshop_flat_sales_order e1
JOIN eshop_flat_sales_order e2
ON e2.customer_email = e1.customer_email
AND e2.created_at < e1.created_at
AND e2.status = 'complete'
LEFT JOIN eshop_flat_sales_order e3
ON e3.customer_email = e1.customer_email
AND e3.created_at < e1.created_at
AND e3.created_at > e2.created_at
AND e3.status = 'complete'
WHERE e1.status = 'complete'
AND e3.customer_email IS NULL
GROUP BY e1.customer_email
日期的格式是什麼?我有點希望'DATE'?還有一個存儲'customer_email's的中央表嗎? – 2012-02-23 13:03:09