Reputation: 43
I want to group the results from one table by two column: created_at
p_id
, I need to group it by p_id
because I need unique values, and I tried using distinct
in order to do that but in my case didn't work how I wanted.
Report.group("date(created_at)").group(:p_id).select("date(created_at) as created_at, count(*) as count, p_id")
r = _
r.count will generate this:
{[Mon, 18 Nov 2013, 11]=>1, [Mon, 18 Nov 2013, 8]=>1, [Mon, 18 Nov 2013, 13]=>1, [Mon, 18 Nov 2013, 12]=>3, [Mon, 18 Nov 2013, 10]=>1, [Mon, 18 Nov 2013, 7]=>1, [Mon, 18 Nov 2013, 3]=>1, [Mon, 18 Nov 2013, 2]=>1, [Mon, 18 Nov 2013, 9]=>1, [Mon, 18 Nov 2013, 14]=>1, [Mon, 18 Nov 2013, 6]=>1}
But I need the result in a different format, what should I add in order to get something like this: {Mon, 18 Nov 2013=>11}
where 11
is the total number of records generated by the above sql statement.
Thank you.
Upvotes: 1
Views: 737
Reputation: 5611
If you just want to count the number of times a date appear on your result, you can do this via simple ruby code:
result = result.inject ({}) do |hash, el|
hash[el[0][0]] ||= 0
hash[el[0][0]] += 1
hash
}
Assuming result is something like this:
{[date1, a] => b, [date1, c] => d, [date2, e] => f}
you'll get
{date1 => 2, date2 => 1}
If you'd like to get the count(*)
value related to a date, change the sum call to this:
hash[el[0][0]] += el[1]
In this case you'll get:
{date1 => b+d, date2 => f}
Upvotes: 1