我有两张桌子
table1(id,dept_id,position_id,pin,名称,last_name,create_time)
table2(dept_id,pin,名称,last_name,zone_id,create_time)
并且它们都具有create_time列,该列以这种格式存储日期和时间(2019-12-01 18:00:00.568) 此列非常重要,我需要匹配日期和时间以使Table1到Table2左连接 我可以与日期进行匹配,但是随着时间的推移,我遇到了问题,两列中的时间总是以秒或毫秒为单位,因此我尝试使用to_char()转换为文本 我需要每天和每小时(24小时)加入两个表格以进行报告
SELECT p.dept_id, p.pin, p.name, p.last_name, p.position_id, a.zone_id, p.create_time::date, to_char(p.create_time::timestamp::time, 'HH24:MI') as time
FROM table1 p
LEFT JOIN table2 a
ON p.create_id::date=a.create_time::date AND
p.pin=a.pin AND p.dept_id=a.dept_id
它给我日期匹配,但不提供时间匹配。我需要这样的东西
SELECT p.dept_id, p.pin, p.name, p.last_name, p.position_id, a.zone_id, p.create_time::date, to_char(p.create_time::timestamp::time, 'HH24:MI') as time1, to_char(a.create_time::timestamp::time, 'HH24:MI') as time2
FROM table1 p
LEFT JOIN table2 a
ON p.create_id::date=a.create_time::date AND
time1 = time2 AND
p.pin=a.pin AND
p.dept_id=a.dept_id
You can use
date_trunc
to truncate the timestamp to the nearest hour andjoin
on that:您可以使用日期/时间不等式。例如:
对于他们来说,这种逻辑是双方在5秒钟之内。