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

时间:2016-05-11 21:39:14

标签: sql postgresql

我有以下情况:

我有员工在工作中登记入住/退房。但他们有10分钟的容忍度。

我对这个观点的后期条目:

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是员工的进度时间。

这是condition contacts.entry_time vs precence_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 TIMESTAMP contacts.entry_time VARCHAR

请帮助我

1 个答案:

答案 0 :(得分:10)

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

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

如果您的时间戳字段是varchar,则可以先将其强制转换为时间戳数据类型,然后减去间隔:

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