的列匹配阵列I具有特定日期称为array_of_dates
的阵列。与表
而且我有一个与列“日期”和“计数”叫my_table
表。
有没有办法让我写活动记录查询来匹配my_table
中的'date'列和array_of_dates
并返回哈希值?所有键从array_of_dates
是日期,所有的值是从my_table
“计数”;返回零作为值如果存在于array_of_dates
日期并不在my_table
列“日期”存在。
在此先感谢。
的列匹配阵列I具有特定日期称为array_of_dates
的阵列。与表
而且我有一个与列“日期”和“计数”叫my_table
表。
有没有办法让我写活动记录查询来匹配my_table
中的'date'列和array_of_dates
并返回哈希值?所有键从array_of_dates
是日期,所有的值是从my_table
“计数”;返回零作为值如果存在于array_of_dates
日期并不在my_table
列“日期”存在。
在此先感谢。
试试这个:
Model.select("date, count").
where(:date => array_of_dates).
reduce(Hash.new(0)){ |h, r| h[r.date] = r.count;h}
的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
,而不是一个普通的加盟。
values
将是0
如果未找到匹配的日期,因为count(t.date_col)
不计算NULL
值。