[英]Postgresql: How to find difference between 2 dates and times in decimal hours?
[英]Postgresql: How to find hours between 2 dates and 2 times?
Postgresql 9.1
我正在尝试使用查询来查找时间表系统的2个日期和2个之间的小数/小数小时差异。 我正在使用查询来确保软件(不是我编写的)没有任何错误。 以下是我正在使用的表中的字段:startdate是Date字段,starttime是Time字段,enddate是Date字段,endtime是Time字段。
示例数据:
我也试过这个sql语句。
SELECT employeetime.dcmasterid as empid,
nonchargeabletime.startdate as ncsdate,
nonchargeabletime.starttime as ncstime,
nonchargeabletime.enddate as ncedate,
nonchargeabletime.endtime as ncetime,
employeetime.dchours as normhrs,
(timestamp (startdate || ' ' || starttime) - timestamp (enddate || ' ' || endtime)) as diffhrs
FROM employeetime, nonchargeabletime
WHERE (nonchargeabletime.employeetime=employeetime.dcautoinc)
AND (nonchargeabletime.startdate >= '2016-04-24')
AND (nonchargeabletime.startdate <= '2016-04-30')
AND (employeetime.dcmasterid IN ('BLURG'))
AND (nonchargeabletime.nonchargeabletype=10)
ORDER BY employeetime.dcmasterid, nonchargeabletime.startdate, nonchargeabletime.starttime;
但是我在startdate
遇到语法错误(timestamp (startdate ||
。
任何人有任何线索如何做到这一点?
谢谢。
向date
添加time
会产生timestamp
,从另一个timestamp
减去一个时间戳会返回一个interval
。
所以你需要做的就是:
(enddate + endtime) - (startdate + starttime) as diff
在SQL的上下文中, interval
很好,但通常在编程语言中难以处理。 您可以使用extract(epoch from interval)
轻松地将interval
转换为秒
如果你想将它转换为小时使用extract
并除以3600
extract(epoch from (enddate + endtime) - (startdate + starttime))/3600 as diff_hours
由于您没有字符串,因此无法使用|| 运算符,但您可以添加时间( http://www.postgresql.org/docs/9.1/static/functions-datetime.html )。
这应该工作(如果你想要整数小时,你可以得到结果):
postgres=# create temporary table ts (startdate date, starttime time, enddate date, endtime time);
CREATE TABLE
postgres=# insert into ts values('2016-05-03', '11:45:15', '2016-05-04', '13:55:43');
INSERT 0 1
postgres=# SELECT startdate,starttime,enddate,endtime, (enddate+endtime)-(startdate+starttime) as interval from ts;
startdate | starttime | enddate | endtime | interval
------------+-----------+------------+----------+----------------
2016-05-03 | 11:45:15 | 2016-05-04 | 13:55:43 | 1 day 02:10:28
(1 row)
postgres=# SELECT startdate,starttime,enddate,endtime, EXTRACT(epoch FROM ((enddate+endtime)-(startdate+starttime)))/3600 as hours from ts;
startdate | starttime | enddate | endtime | hours
------------+-----------+------------+----------+------------------
2016-05-03 | 11:45:15 | 2016-05-04 | 13:55:43 | 26.1744444444444
(1 row)
WITH zooi(startdate,starttime, enddate,endtime) AS (
VALUES('2016-04-29'::date , '23:00:00'::time
,'2016-04-30'::date , '01:30:00'::time )
)
, stamps (sta, sto) AS (
select (z.startdate+z.starttime)::timestamp
, (z.enddate+z.endtime)::timestamp
FROM zooi z
)
SELECT sta,sto
, age(sto,sta) AS how_old
, (sto-sta)::time AS diff
FROM stamps;
下一步是将时间(或间隔)结果转换为天或小时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.