Postgresql 9.1
我尝试使用查询来查找时间表系统的2个日期和2个时间之间的小数/小数小时差异。我使用查询来确保软件(不是我编写的)没有任何错误。以下是表I中使用的字段:startdate是Date字段,starttime是Time字段,enddate是Date字段,endtime是Time字段。
我看过date time docs for 9.1但仍未找到我需要的东西。
示例数据:
我也试过这个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 ||
。
任何人都有任何线索如何做到这一点?
谢谢。
答案 0 :(得分:7)
将time
添加到date
会产生timestamp
并从另一个时间戳中减去一个时间戳会返回interval
。
所以你需要做的就是:
(enddate + endtime) - (startdate + starttime) as diff
interval
在SQL的上下文中很好用,但通常在编程语言中难以处理。您可以使用interval
extract(epoch from interval)
转换为秒
如果您想将其转换为小时数,请使用extract
并除以3600
extract(epoch from (enddate + endtime) - (startdate + starttime))/3600 as diff_hours
答案 1 :(得分:1)
由于您没有字符串,因此无法使用||运算符,但您只需添加时间(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)
答案 2 :(得分:0)
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;
下一步是将时间(或间隔)结果转换为天或小时。