简体   繁体   中英

Timestamp Difference In minutes for PostgreSQL

I have the following query:

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

That works fine for mysql but postgresql is complaining about the TIMESTAMPDIFF ... are there ways to achieve this behaviour in both DBMS with the same query?

Btw, works.begin_at and works.finish_at are defined as time

You can just substract the two times: this gives you an interval, which you can turn to seconds with extract() , and then to minutes using arithmetics:

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

This returns an integer value. If you want the decimal part as well, then:

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

EXTRACT(EPOCH FROM works.begin_at) - EXTRACT(EPOCH FROM works.finish_at))/3600 gives you the hours difference

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM