首页 > 解决方案 > 查询今天未完成调查的用户并收到错误

问题描述

我有一个正在开发的功能,我需要我的 PostgreSQL 数据库来返回今天尚未完成调查的所有用户。

select distinct *
from users 
left join survey_results
on users.user_id = survey_results.user_id
where customer_id = '9000'
and survey_results.created_at < (DATE_PART('year', survey_results.created_at) = (SELECT EXTRACT(YEAR FROM CURRENT_TIMESTAMP))
                                  AND DATE_PART('month', survey_results.created_at) = (SELECT EXTRACT(MONTH FROM CURRENT_TIMESTAMP)) 
                                  AND DATE_PART('day', survey_results.created_at) = (SELECT EXTRACT(DAY FROM CURRENT_TIMESTAMP)))

我正在使用左联接加入我的调查结果表并按 customer_id 过滤,而survey_results.created < 今天在哪里,但我正在使用日期部分并提取来获取日期。如果有更好的方法可以做到这一点,但这就是我所拥有的。

我在运行查询而不是结果时收到此输出。

ERROR:  operator does not exist: timestamp with time zone < boolean
LINE 6: and survey_results.created_at < (DATE_PART('year', survey_re...
                                      ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
SQL state: 42883
Character: 155

标签: sqlpostgresqldatetime

解决方案


与其使用 datepart,不如将其与 current_date 进行比较 -

select distinct *
from users 
left join survey_results
on users.user_id = survey_results.user_id
where customer_id = '9000'
and survey_results.created_at < CURRENT_DATE

如果您的survey_results.created_at 列是时间戳,请使用日期函数将其转换为日期,然后将其与current_date 进行比较 -

select distinct *
from users 
left join survey_results
on users.user_id = survey_results.user_id
where customer_id = '9000'
and DATE(survey_results.created_at) < CURRENT_DATE

推荐阅读