Subquery To retrieve count with group by clause

Hello All,

So. Here is my issue. I am trying to follow this example:

I need a count of items, grouped by a repid. Here goes.

In my kit model:

public $kit_count;


array('kitId, bid, datePlaced, note, partId, kit_count’, ‘safe’, ‘on’=>‘search’),


‘branchR’ => array(self::BELONGS_TO, ‘Branch’, ‘bid’),

public function sumByBranch()


	// @todo Please modify the following code to remove attributes that should not be searched.

	$table = Branch::model()->tableName();

( I feel like this is the SQL statement that i need to execute correctly)

	$kitCount = "(SELECT count(b.repid) 

					FROM $table b

					WHERE =

					group by b.repid)";

( This is the statement the documentation would have me believe is correct)

	// $kitCount = "(SELECT count(*) 

	// 				FROM $table b

	// 				WHERE =";

	$criteria=new CDbCriteria;

	$criteria->with = array('branchR');

	$criteria->group = 'branchR.repid';

	$criteria->select = array(


		$kitCount." as kit_count",



	return new CActiveDataProvider($this, array(




In my gridview:


			'name' => 'kit_count',

			'header' => 'Kits Placed',

			'filter' => false,


Here is my issue. I have sales reps that place "kits." I need to track how many are placed, and they are placed with "branches" so. each kit has a branch id, so i dump the kits table and there are 9 kits with branch id "12345" and then 1 kit with "6789". When i use the above code, it seperates and shows that "12345" has 1 kit placed, and "6789" has 1 kit placed. Its doing a distinct by branch id i think. but, branch 12345 should have 9. Basically the following is the raw sql that give me the correct results.

select count(branch.repid) as branchCount, branch.repid from branchKits, branch where = group by branch.repid;

Without the group by clause, the results make it distinct by branch, giving a value of 1 to the count, basically telling me that there is one entry at least of that branch in the table.

A rep may have multiple branches, so i join to the branch table, and the group by clause is grouped by the name of the rep, not the branch id. Any help would be appreciated, let me know if you need more explanation.