[英]Left Join with date and timestamp columns in postgreSQL
I have two tables我有两张桌子
table1 (id, dept_id, position_id, pin, name, last_name, create_time) table1 (id, dept_id, position_id, pin, name, last_name, create_time)
table2 (dept_id, pin, name, last_name, zone_id, create_time) table2 (dept_id, pin, name, last_name, zone_id, create_time)
and they have both create_time column which stores date and time in this format (2019-12-01 18:00:00.568) this column very important I need to match the dates and time to make Left join Table1 to Table2 I can make a match with the date but with time I have a problem, the time in both columns always have the difference in second or in milliseconds so I try to convert to text with to_char() I need to join two tables daily and hourly manner (24 hours) to make the report并且他们都有create_time列,它以这种格式存储日期和时间(2019-12-01 18:00:00.568)这个列非常重要我需要匹配日期和时间以使 Left join Table1 to 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 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
It gives me date matches but doesn't provide time matches.它给了我日期匹配但不提供时间匹配。 I need something like this
我需要这样的东西
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 hour and join
on that:您可以使用
date_trunc
将时间戳截断为小时并join
:
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 date_trunc('hour', p.create_time) = date_trunc('hour', a.create_time)
AND p.pin=a.pin
AND p.dept_id=a.dept_id
You can use date/time inequalities.您可以使用日期/时间不等式。 For instance:
例如:
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.pin = a.pin AND
p.dept_id = a.dept_id AND
p.create_id >= a.create_time - INTERVAL '5 second' AND
p.create_id <= a.create_time + INTERVAL '5 second';
This logic is for them being within 5 seconds on either side.这个逻辑适用于他们在任何一方都在 5 秒内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.