我有一个Rails应用程序,它使用如下所示的自定义sql字符串(带有postgres数据库)。该字符串工作正常。我正在尝试在查询中添加时间条件,以便我只检索来自answer_votes,best_answers和过去7天内创建的贡献的记录。因此,我得到今天的日期并减去7天
date = Date.today - 7
并将下面的sql字符串中的语句替换为类似
的语句(select Coalesce(sum(value),0) from answer_votes where (answer_votes.user_id = users.id) AND (answer_votes.created_at <= #{date}))
然而,它给了我几个错误
PG::Error: ERROR: operator does not exist: timestamp without time zone <= integer
你能告诉我这样做的正确方法吗?请注意,虽然我只展示了我对answer_votes的尝试,但我会尝试为best_answers和贡献做同样的事情,但是,解决方案将是相同的(我假设)。
sql_string = "with cte_scoring as (
select
users.id, users.name, users.email,
(select Coalesce(sum(value),0) from answer_votes where answer_votes.user_id = users.id) +
(select Coalesce(sum(value),0) from best_answers where best_answers.user_id = users.id) +
(select Coalesce(sum(value),0) from contributions where contributions.user_id = users.id) total_score
from
users join
contacts on (contacts.user_id = users.id)
where
users.lawyer = 'true')
select id,
name,
email,
total_score
from cte_scoring
order by total_score desc
limit 2 "
答案 0 :(得分:1)
您可以使用内置的Postgres功能:
where . . . created_at <= Current_Date - interval '7 day'
变量替换可能出现问题。您可能需要围绕日期变量使用单引号。但是,在数据库中执行此操作更简单。