count
の方法は、あなたと同じように機能しません。
select count(distinct(id), year(created_at), month(created_at))
from users
group by year(created_at), month(created_at)
このSELECT節は非常に面倒ですが、MySQLは通常のややこしい方法でそれを解消します。私はこのクエリをしたいと思う:
select count(distinct(id)), year(created_at), month(created_at)
from users
group by year(created_at), month(created_at)
私はおそらくこのようなselect_all
に直行したい:
a = User.connection.select_all(%q{
select count(distinct(id)) as c, year(created_at) as y, month(created_at) as m
from users
group by y, m
})
それともあなたはこのようにそれを行うことができます:
a = User.connection.select_all(
User.select('count(distinct(id)) as c, year(created_at) as y, month(created_at) as m').
group('y, m')
)
ものが得られます配列a
、ハッシュのc
、y
、m
のようなキー:
a = [
{ 'c' => '23', 'y' => '2010', 'm' => '11' },
{ 'c' => '1', 'y' => '2011', 'm' => '1' },
{ 'c' => '5', 'y' => '2011', 'm' => '3' },
{ 'c' => '2', 'y' => '2011', 'm' => '4' },
{ 'c' => '11', 'y' => '2011', 'm' => '8' }
]
次にデータ論争のビットは、あなたが仕事を終えるために必要なすべてのです:
h = a.group_by { |x| x['y'] }.each_with_object({}) do |(y,v), h|
h[y.to_i] = Hash[v.map { |e| [e['m'].to_i, e['c'].to_i] }]
end
# {2010 => {11 => 23}, 2011 => {1 => 1, 3 => 5, 4 => 2, 8 => 11}}