Skip to content

Instantly share code, notes, and snippets.

@drewgillson
Created January 6, 2012 07:08
Show Gist options
  • Save drewgillson/1569465 to your computer and use it in GitHub Desktop.
Save drewgillson/1569465 to your computer and use it in GitHub Desktop.
Customer report from Magento
-- assuming Magento 1.6.1 data model
SELECT DISTINCT customer_email,
COUNT(*) AS purchases,
(SELECT LEFT(created_at,11) FROM `sales_flat_order` WHERE customer_email = a.customer_email ORDER BY created_at DESC LIMIT 0,1) AS last_purchase,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%IB%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS icebreaker,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%TNF%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS the_north_face,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%MHW%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS mountain_hardwear,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%MAR%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS marmot,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%LOLE%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS lole,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%SW%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS smartwool,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%OSP%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS osprey,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%SOR%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS sorel,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%ARC%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS arcteryx,
(SELECT COUNT(*) FROM sales_flat_order_item WHERE product_type = 'simple' AND sku LIKE '%COL%' AND order_id IN (SELECT entity_id FROM `sales_flat_order` WHERE customer_email = a.customer_email)) AS columbia
FROM `sales_flat_order` AS a
GROUP BY customer_email
ORDER BY COUNT(*) DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment