Let's start with thinking about the SQL, not Magento (we'll get there later). I would write it as such (ignoring timezones for simplicity):
SELECT sku,SUM(qty_ordered) FROM sales_flat_order_item
WHERE created_at BETWEEN NOW()-INTERVAL 2 WEEK AND NOW()
GROUP BY sku
That query works (I tested). So, how would we go about writing this query in Magento?
- Firstly, we see that it's entirely based on
sales_flat_order_item - Magento has a special resource collection for this table; we can make use of that.
- We see that it uses a
SUM in one of the columns
WHERE has a
BETWEEN clause - we can probably use
Zend_Db_Expr to output our custom rolling 2-weeks timeframe.
- Finally, it has a
Let's see if we can't put it together, then, with a quick call to
reset to make sure that we only get the columns we define, and nothing else:
$query = Mage::getResourceModel('sales/order_item_collection');
->where(new Zend_Db_Expr('created_at BETWEEN NOW()-INTERVAL 2 WEEK AND NOW()'))
A simple echo of
$query->getSelect() shows us that the query is formatted quite well:
SELECT `main_table`.`sku`, SUM(qty_ordered) FROM `sales_flat_order_item` AS `main_table` WHERE (created_at BETWEEN NOW()-INTERVAL 2 WEEK AND NOW()) GROUP BY `sku`
In the future you may want to filter this report based on order status (joining to another table) or you may want to make sure that the time zones are accurate (right now it's reporting based on GMT).
Joining is simple:
->join(array('e' => 'sales_flat_order'),'main_table.order_id = e.entity_id')
But adding time zones can get complicated. Look into
Mage_Core_Model_Date for some methods that convert timestamps to and from GMT. Also look into the the sales reports collection.
Hope that helps! Best of luck.