我正在开发一个功能,我需要我的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
与其使用日期部分,不如将其与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
使用NOT EXISTS
和today()
而不是CURRENT_TIMESTAMP
:
SELECT *
FROM users
WHERE NOT EXISTS (
SELECT
FROM survey_results
WHERE users.user_id = survey_results.user_id
AND survey_results.created_at < today()
)
AND customer_id = '9000'
返回所有在今天之前未完成调查的人。