sql - 按 created_at 搜索时 PostgreSQL 的结果不正确

标签 sql postgresql

我有以下查询:

SELECT
  COUNT(sr.id) AS total,
  COUNT(sr.id) FILTER (where (raw #>> '{survey, declined}' IS NULL) OR (raw #>> '{survey, declined}' = 'false')) AS completed,
  COUNT(sr.id) FILTER (WHERE (raw #>> '{survey, declined}' = 'true')) AS denied
FROM survey_results sr
LEFT JOIN clients c ON c.id = sr.client_id
LEFT JOIN facilities f ON f.client_id = c.id
WHERE
    sr.created_at >= '2005-07-01T08:00:00+00:00' AND 
    sr.created_at <= '2005-08-02T07:59:59+00:00' AND
    4 IS NULL OR sr.client_id = 4 AND 
    NULL IS NULL OR f.id = NULL
;

问题是没有使用那些 created_at 过滤器。它还返回在不同时间创建的记录。我该如何解决这个问题?

最佳答案

你需要括号:

WHERE (sr.created_at >= '2005-07-01T08:00:00+00:00' AND 
       sr.created_at <= '2005-08-02T07:59:59+00:00'
      ) AND
      (4 IS NULL OR sr.client_id = 4) AND 
      (NULL IS NULL OR f.id = NULL)

虽然没有必要,但我会使用带有 tz 的显式时间戳来编写 tis,并将逻辑简化为:

WHERE (sr.created_at >= '2005-07-01T08:00:00+00:00'::timestamptz AND 
       sr.created_at < '2005-08-02T08:00:00+00:00'::timestamptz
      ) AND
      (4 IS NULL OR sr.client_id = 4) AND 
      (NULL IS NULL OR f.id = NULL)

关于sql - 按 created_at 搜索时 PostgreSQL 的结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45954904/

相关文章:

ruby-on-rails - 如何更新rails中的 bool 值

postgresql - 索引的 Postgres pg_dump 缓存查找失败

postgresql - 在 postgreSQL 表中导入时如何识别文本/csv 文件标题行中的字段名?

php - SQL 双选

mysql - 从子查询中检索多列

失败/不正确查询的 SQL Server 查询日志?

java - 没有提取任何数据。为什么?

postgresql - Postgres - 基于连续值的排名

ruby-on-rails - 带有或用于数组输入的查询链的 Rails

mysql - 将变量传递给 KNIME 中的 SQL 语句