按周分组rails记录并添加它们

时间:2015-02-05 09:43:41

标签: ruby-on-rails ruby group-by

我使用Rails 4.1和Ruby 2.1以及Postgresql

我有一个带有日期列(日期时间)和值列(十进制)的记录表。我想添加同一周的所有值列,说明此处可用用户的时区:current_user.time_zone

记录可能在1000年左右,因此速度很重要。

我像这样使用了groupdate gem:

Record.where(:user_id => current_user.id).group_by_week(:day, time_zone: current_user.time_zone).count

但是它返回了4个日期时间的哈希值,总共有9条记录。

来自BroiSatse的解决方案:

Record.where(:user_id => current_user.id).group_by_week(:day,time_zone:current_user.time_zone).sum(:value)

但是当:值为json这是我得到的错误:

SELECT SUM(value->'430') AS sum_value_430, (DATE_TRUNC('week', (day::timestamptz - INTERVAL '6 day' - INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai') + INTERVAL '6 day' + INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai' AS week FROM "eats"  WHERE "eats"."user_id" = 53 AND (day IS NOT NULL) GROUP BY (DATE_TRUNC('week', (day::timestamptz - INTERVAL '6 day' - INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai') + INTERVAL '6 day' + INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai'
PG::UndefinedFunction: ERROR:  function sum(json) does not exist
LINE 1: SELECT SUM(value->'430') AS sum_total_nutriti...
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
: SELECT SUM(value->'430') AS sum_value_430, (DATE_TRUNC('week', (day::timestamptz - INTERVAL '6 day' - INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai') + INTERVAL '6 day' + INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai' AS week FROM "eats"  WHERE "eats"."user_id" = 53 AND (day IS NOT NULL) GROUP BY (DATE_TRUNC('week', (day::timestamptz - INTERVAL '6 day' - INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai') + INTERVAL '6 day' + INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai'
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  function sum(json) does not exist
LINE 1: SELECT SUM(value->'430') AS sum_total_nutriti...
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
: SELECT SUM(value->'430') AS sum_value_430, (DATE_TRUNC('week', (day::timestamptz - INTERVAL '6 day' - INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai') + INTERVAL '6 day' + INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai' AS week FROM "eats"  WHERE "eats"."user_id" = 53 AND (day IS NOT NULL) GROUP BY (DATE_TRUNC('week', (day::timestamptz - INTERVAL '6 day' - INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai') + INTERVAL '6 day' + INTERVAL '0' hour) AT TIME ZONE 'Asia/Shanghai'

0 个答案:

没有答案