Magento Snippet: Use a Group By clause on a collection model

August 17th, 2016

Warning: This post is 7 years old. Some of this information may be out of date.

Here's a Magento snippet showing how to use a Group By clause on a Magento collection model.

<?php

// ....

$collection = Mage::getModel('sales/order_item')->getCollection();
$collection
    ->addAttributeToFilter('updated_at', array('gt' => $this->reportStartDate)) 
    ->addAttributeToFilter('updated_at', array('lt' => $this->reportEndDate));

// this is where we add the group by  
$collection->getSelect()->group('main_table.sku');

$collection->setOrder('updated_at', 'DESC');