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}}