PostgreSQL的时间戳差异(以分钟为单位)

时间:2020-11-06 22:59:03

标签: sql postgresql time date-arithmetic

我有以下查询:

Select works.id, works.client_id, COALESCE(TIMESTAMPDIFF(MINUTE,works.begin_at,works.finish_at), 0) / 60 * (clients.worker_cost_hourly * works.number_of_workers + works.machines *             clients.machine_cost_hourly) as cost
from works join clients on works.client_id = clients.id
where works.paid = 0

这对于mysql来说很好,但是postgresql抱怨TIMESTAMPDIFF ...是否可以通过相同的查询在两个DBMS中实现这种行为?

顺便说一句,works.begin_atworks.finish_at被定义为time

2 个答案:

答案 0 :(得分:1)

您可以减去两次:这为您提供了一个间隔,您可以使用extract()将其转换为秒,然后使用算术将其转换为分钟:

extract(epoch from works.finish_at - works.begin_at) / 60

这将返回一个整数值。如果还需要小数部分,则:

extract(epoch from works.finish_at - works.begin_at) / 60.0 

答案 1 :(得分:1)

EXTRACT(EPOCH FROM works.begin_at)-EXTRACT(EPOCH FROM works.finish_at))/ 3600为您提供时差

Select works.id, works.client_id
, COALESCE(T(EXTRACT(EPOCH FROM works.begin_at) - EXTRACT(EPOCH FROM works.finish_at))/3600, 0) / 60 * (clients.worker_cost_hourly * works.number_of_workers 
+ works.machines * clients.machine_cost_hourly) as cost
from works join clients on works.client_id = clients.id
where works.paid = 0