Magento 2 SQL queries › Customers
Who are our top 20 customers by total spend this year?
Short answer: Magento's Order Total report ranks customers after a statistics refresh. The query below also subtracts refunds.
In the Magento admin
- Refresh statistics, then open Reports › Customers › Order Total.
- Set the period to this year and Show By to Year.
With one query
These queries only read data. Run them on a copy of your database if you can, or ask your developer to. If your tables have a prefix (set in app/etc/env.php), add it to each table name.
Works on Magento Open Source and Adobe Commerce:
SELECT o.customer_id,
MAX(o.customer_email) AS email,
MAX(CONCAT_WS(' ', o.customer_firstname, o.customer_lastname)) AS name,
COUNT(*) AS orders,
ROUND(SUM(o.base_grand_total - IFNULL(o.base_total_refunded, 0)), 2) AS net_spend
FROM sales_order o
WHERE o.customer_id IS NOT NULL
AND o.state <> 'canceled'
AND o.created_at >= DATE_FORMAT(CURRENT_DATE, '%Y-01-01')
GROUP BY o.customer_id
ORDER BY net_spend DESC
LIMIT 20;
Good to know
- Guest orders have no
customer_idand are left out. To include them, group bycustomer_emailinstead. - This is personal data: keep the result inside your team.