sql - 如何从 postgreSQL 中的时间戳中减去/添加分钟

标签 sql postgresql

我有以下场景:

我有员工登记他们的工作 checkin / checkout 。但他们有 10 分钟的容忍度。

我使用此 View 得到的迟到条目:

CREATE OR REPLACE VIEW employees_late_entries
(
  id,
  created_datetime,
  entry_datetime,
  contact_id,
  contact_name,
  user_id,
  employees_perm_id
)
AS 
 SELECT precence_records.id,
    precence_records.created AS created_datetime,
    ("substring"(precence_records.created::text, 0, 11) || ' '::text) || contacts.entry_time::text AS entry_datetime,
    contacts.id AS contact_id,
    contacts.name AS contact_name,
    precence_records.user_id,
    precence_records.employees_perm_id
   FROM precence_records,
    contacts
  WHERE 
    precence_records.type::text = 'entry'::text AND 
    contacts.employee = true AND 
    contacts.id = precence_records.contact_id AND 
    ( ("substring"(precence_records.created::text, 0, 11) || ' '::text) || contacts.entry_time::text) < precence_records.created::text AND 
    precence_records.employees_perm_id IS NULL;

precence_records.created 是签到时间,contacts.entry_time 是员工的日程安排输入时间。

这是 contacts.entry_timeprecence_records.created 获取迟到条目的条件:

 ( ("substring"(precence_records.created::text, 0, 11) || ' '::text) || contacts.entry_time::text) < precence_records.created::text

所以我想做这样的事情:

 (  ("substring"(precence_records.created::text, 0, 11) || ' '::text) || (contacts.entry_time::text + 10 MINUTES)  ) < precence_records.created::text

数据类型:

precence_records.created 时间戳 contacts.entry_time VARCHAR

你能帮帮我吗

最佳答案

PostgreSQL 中的日期、时间和时间戳可以添加/减去 INTERVAL 值:

SELECT now()::time - INTERVAL '10 min'

如果你的timestamp字段是varchar,你可以先转成timestamp数据类型再减去interval:

 ( (left(precence_records.created::text, 11) || ' ') ||
   (contacts.entry_time::time + INTERVAL '10min')::text )::timestamp <
 precence_records.created::timestamp

关于sql - 如何从 postgreSQL 中的时间戳中减去/添加分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173732/

相关文章:

mysql - 根据MYSQL表中列的值创建新列

mysql - 关于select ... in的sql性能

ruby-on-rails - 创建一个无数据库的 rails 模型,作为在 elasticsearch 中索引数据的 View

ruby-on-rails - PG 数据库 :structure:load results in sh error

sql - 在 SQL (Postgresql) 中检查是否可以预订

mysql - 带加法的 SQL 子查询

sql - 设计此特定数据库/SQL 问题的最佳方法是什么?

java - Spring Boot 到 Postgres 数据库 - 驱动程序问题

postgresql - Postgres 备份大小是数据库大小本身的两倍

postgresql - 我该如何优化这个 : Many Postgres triggers calling the same function within a transaction