Skip to content

Instantly share code, notes, and snippets.

@tegansnyder
Created January 31, 2014 15:41
Show Gist options
  • Save tegansnyder/8734474 to your computer and use it in GitHub Desktop.
Save tegansnyder/8734474 to your computer and use it in GitHub Desktop.
Magento - Sum of All Orders by Month and Year Breakdown includes Discount Sums
SELECT sub_query.month_ordered,
sub_query.year_ordered,
SUM(sub_query.base_subtotal) AS sum_base_subtotal,
SUM(sub_query.discount_amount) AS sum_discount_amt,
SUM(sub_query.order_qty) AS sum_total_item_count,
COUNT(sub_query.entity_id) AS total_orders
FROM
(SELECT so.entity_id,
MONTH(so.created_at) AS month_ordered,
YEAR(so.created_at) AS year_ordered,
so.base_subtotal,
so.discount_amount,
so.total_item_count AS order_qty,
so.increment_id
FROM `sales_flat_order` AS so
INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
GROUP BY entity_id) AS sub_query
GROUP BY sub_query.month_ordered
ORDER BY year_ordered DESC,
month_ordered DESC
@tegansnyder
Copy link
Author

want to grab the first quarter sales

SELECT SUM(sum_base_subtotal) - SUM(sum_discount_amt) as total FROM (
    SELECT sub_query.month_ordered,
           sub_query.year_ordered,
           SUM(sub_query.base_subtotal) AS sum_base_subtotal,
           SUM(sub_query.discount_amount) AS sum_discount_amt,
           SUM(sub_query.order_qty) AS sum_total_item_count,
           COUNT(sub_query.entity_id) AS total_orders
    FROM
      (SELECT so.entity_id,
              MONTH(so.created_at) AS month_ordered,
              YEAR(so.created_at) AS year_ordered,
              so.base_subtotal,
              so.discount_amount,
              so.total_item_count AS order_qty,
              so.increment_id
       FROM `sales_flat_order` AS so
       INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
       GROUP BY entity_id) AS sub_query
    GROUP BY sub_query.month_ordered
    ORDER BY year_ordered DESC,
             month_ordered DESC
 ) subq
 WHERE month_ordered >= 1 AND month_ordered <= 3 AND year_ordered = "2014"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment