在PostgreSQL中使用时间戳变量在小时之间对同一日期进行观测

ruyhziif  于 2023-02-15  发布在  PostgreSQL
关注(0)|答案(1)|浏览(104)

我试图运行一个select来选择同一日期中不同时间段的数据。下面的代码展示了这个想法,但它不起作用。我的datahora变量是一个时间戳,格式如下:'yyyy-mm-dd hh 24:mi:ss”,显示为2023-02-13 15:30:30。我如何运行它?

select tr.tick, tr.cot, tr2.cot, tr2.cot-tr.cot as dif
  from tb_registros tr 
    join tb_registros tr2 on to_char(tr.datahora, 'yyyy-mm-dd') = to_char(tr2.datahora, 'yyyy-mm-dd') and to_char(tr.datahora, 'hh24:mi:ss') between '08:55:00' and '08:56:10'  and to_char(tr2.datahora, 'hh24:mi:ss') between '09:10:00' and '09:11:10'
where tick = 'ANY'
ghhkc1vu

ghhkc1vu1#

最好是对正确的日期/时间戳或时间值而不是字符串进行操作,假设列datahora实际上定义为timestamp,将其转换为date将删除时间部分,而将其转换为time值将删除“day”:

select tr.tick, tr.cot, tr2.cot, tr2.cot-tr.cot as dif
from tb_registros tr 
  join tb_registros tr2 
    on tr.datahora::date = tr2.datahora::date
   and tr.datahora::time between '08:55:00' and '08:56:10'  
   and tr2.datahora::time between '09:10:00' and '09:11:10'
where tick = 'ANY'

::date是Postgres专有的强制转换运算符。如果您更喜欢ANSISQL,可以使用cast(... as date)

相关问题