2013年6月7日金曜日

[cakphp] 特定のカラムのグループごとの最大値が格納されている行

特定のカラムのグループごとの最大値が格納されている行 「物品ごとに最高値を付けている業者 (複数可) は?」 MySQLのドキュメントによると次のようになる。
1
2
3
4
5
6
7
8
9
10
11
12
13
SELECT article, dealer, price
FROM   shop s1
WHERE  price=(SELECT MAX(s2.price)
              FROM shop s2
              WHERE s1.article = s2.article);
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0001 | B      |  3.99 |
|    0002 | A      | 10.99 |
|    0003 | C      |  1.69 |
|    0004 | D      | 19.95 |
+---------+--------+-------+
これをcakephp風に書き直すと以下のようになる。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$db = $this->Shop->getDataSource();
$subQuery = $db->buildStatement(
 array(
  'fields' => array('MAX(s2.price)'),
  'table' => $db->fullTableName($this->Shop),
  'alias' => 's2',
  'limit' => null,
  'offset' => null,
  'joins' => array(),
  'conditions' => array('Shop.article' => 's2.article'),
  'order' => null,
  'group' => null,
 ),
 $this->Shop
);
return $this->Shop->find('all',
 array(
  'fields' => array('article', 'dealer', 'price'),
  'conditions' => array(
   "Shop.price = ($subQuery)",
  ),
 )
);