Skip to content

Instantly share code, notes, and snippets.

@rafaelstz
Created November 6, 2017 19:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rafaelstz/fb691cb3d583ea95559c627b2cb4c941 to your computer and use it in GitHub Desktop.
Save rafaelstz/fb691cb3d583ea95559c627b2cb4c941 to your computer and use it in GitHub Desktop.
Magento 1 - SQL to get the each customer sales and orders total
# Get the each customer sales and orders total
SELECT
-- Round to two decimal places and prepend with $
CONCAT('$', FORMAT(SUM(sales_flat_order.`grand_total`), 2)) AS 'Lifetime Sales',
COUNT(sales_flat_order.entity_id) AS 'Orders',
customer_entity.email AS 'Email',
MAX(sales_flat_order.created_at) AS 'Most Recent Order Date'
FROM `customer_entity`
LEFT JOIN sales_flat_order ON customer_entity.entity_id = sales_flat_order.customer_id
GROUP BY customer_entity.entity_id
ORDER BY SUM(sales_flat_order.`grand_total`) DESC
LIMIT 500;
# Get Orders Status
SELECT
sales_order_status.label AS 'Status',
COUNT(sales_flat_order.entity_id) AS 'Orders'
FROM sales_flat_order
LEFT JOIN sales_order_status ON sales_flat_order.status = sales_order_status.status
GROUP BY sales_flat_order.status
ORDER BY COUNT(sales_flat_order.entity_id) DESC;
# Get the each month Order Status
SELECT
-- "Year - Month"
CONCAT(YEAR(sales_flat_order.created_at), ' - ', MONTHNAME(sales_flat_order.created_at)) AS 'Month',
SUM(IF(`status` = 'canceled', 1, 0)) AS 'Canceled',
SUM(IF(`status` = 'closed', 1, 0)) AS 'Closed',
SUM(IF(`status` = 'complete', 1, 0)) AS 'Complete',
-- Custom status
SUM(IF(`status` = 'complete_partially_shipped', 1, 0)) AS 'Partially Shipped',
SUM(IF(`status` = 'processing', 1, 0)) AS 'Processing',
-- Custom status
SUM(IF(`status` = 'shipped', 1, 0)) AS 'Shipped'
FROM sales_flat_order
GROUP BY MONTH(sales_flat_order.created_at);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment