查询结果不同

时间:2020-02-28 12:10:41

标签: sql postgresql

我有两个类似的查询:

select COUNT(*), to_char(start_time,'YYYYMMDD') from EXECUTIONS where 
to_char(start_time,'YYYYMMDD') >= '20200101' and
to_char(start_time,'YYYYMMDD') <= '20200131' 
AND SERVER IN ('PRO','PRE','DE')
group by to_char(start_time,'YYYYMMDD') ORDER BY to_char(start_time,'YYYYMMDD')  ASC ;
---------
select
    SERVER,
    APP,
    sum(case when ended_status = 16 then 1 else 0 end) OK,
    sum(case when ended_status = 32 then 1 else 0 end) BAD,
        count(ended_status) TOTAL
from EXECUTIONS
where start_time >= '20200101' and start_time <= '20200131'
and SERVER in ('PRO','PRE','DE')
group by
    SERVER,
    APP
order by SERVER,APP;

我已经看到,在最后一个查询中,该查询中不包含该月的最后一天(2020131)。

我不明白为什么。你能帮我吗?

1 个答案:

答案 0 :(得分:3)

它有一个时间部分。正确的逻辑是:

where start_time >= '20200101' and
      start_time <  '20200201'

这对于日期和日期/时间都是安全的。我强烈建议在 all 日期比较中使用这种不等式,这样您就不必担心时间部分是否是值的一部分。以上是索引安全的。

相关问题