0

I have an array of certain dates called array_of_dates.

And I have a table called my_table with columns 'date' and 'count'.

Is there a way I can write an active records query to match the 'date' column in my_table with array_of_dates and return hashes ? All keys being the dates from array_of_dates, and all the values being the 'count' from my_table; returning zero as the value if a date present in array_of_dates doesn't exist in column 'date' of my_table.

Thanks in advance.

4

2 回答 2

1

SQL 可能如下所示:

SELECT date_col AS key, count(t.date_col) AS value
FROM  (
   SELECT unnest('{2012-07-08, 2012-07-09, 2012-07-10}'::date[]) AS date_col
   ) x
LEFT   JOIN tbl t USING (date_col)
GROUP  BY date_col;

关键元素是带有unnest()LEFT JOIN代替普通连接的子查询。

values0如果没有找到匹配的日期,将是因为count(t.date_col)不计算NULL值。

于 2012-07-09T17:31:18.350 回答
1

尝试这个:

Model.select("date, count").
  where(:date => array_of_dates).
    reduce(Hash.new(0)){ |h, r| h[r.date] = r.count;h}
于 2012-07-09T18:07:01.450 回答