[英]Find closest match to value in another table
我有一个 table_a,其中 PostgreSQL 13 中的每个时间戳都有许多行和列。我试图找到 X 列中的值最接近从另一个表获得的基准值的行。 第二个表对于每个时间戳只有一个基准值。 对于每个时间戳,我需要返回 table_a 的大部分列。 直接提供基准值时,下面的查询可以正常工作。
如何从 table_b 获取基准值以在此查询中使用?
简单地将 table_b.benchmark 替换为 (SELECT benchmark FROM table_b WHERE table_a.timestamp = table_b.timestamp) 会导致“关系“t1”不存在”错误。
也想不出一个有效的连接。
表_a:
+-----------------+-----+---------------+
| timestamp | x | other_columns |
+-----------------+-----+---------------+
| 2020-01-01 8:00 | 100 | |
| 2020-01-01 8:00 | 200 | |
| 2020-01-01 8:00 | 300 | |
| 2020-01-01 8:00 | 400 | |
| 2020-01-01 8:00 | 500 | |
| ... | | |
| 2020-01-01 9:00 | 100 | |
| 2020-01-01 9:00 | 200 | |
| 2020-01-01 9:00 | 300 | |
| 2020-01-01 9:00 | 400 | |
| 2020-01-01 9:00 | 500 | |
| ... | | |
+-----------------+-----+---------------+
表_b:
+-----------------+-----------+
| timestamp | benchmark |
+-----------------+-----------+
| 2020-01-01 8:00 | 340 |
| 2020-01-01 9:00 | 380 |
| ... | |
+-----------------+-----------+
预期结果:
+-----------------+-----+
| timestamp | x |
+-----------------+-----+
| 2020-01-01 8:00 | 300 |
| 2020-01-01 9:00 | 400 |
| ... | |
+-----------------+-----+
SQL查询:
WITH date_filter AS (
SELECT *
FROM table_a
WHERE timestamp >= {start_date} and timestamp < {end_date}
)
SELECT DISTINCT t1.timestamp, t1.x, t1.etc
FROM date_filter AS t1
INNER JOIN (
SELECT timestamp, MIN(ABS(x - (table_b.benchmark))) AS target_value
FROM t1
GROUP BY timestamp
) AS t2
ON t2.timestamp = t1.timestamp AND t2.target_value = ABS(x - (table_b.benchmark))
ORDER BY timestamp ASC;```
我建议横向连接:
select b.*, a.x
from table_b b left join lateral
(select a.*
from table_a a
where a.timestamp = b.timestamp
order by abs(a.x - b.benchmark)
limit 1
) b
on 1=1;
一种选择使用横向连接:
select b.timestamp, a.x
from table_b b
cross join lateral (
select a.*
from table_a a
where a.timestamp = b.timestamp
order by abs(a.x - b.benchmark)
limit 1
) a
您还可以使用distinct on
:
select distinct on (b.timestamp) b.timestamp, a.x
from table_b b
inner join table_a a on a.timestamp = b.timestamp
order by b.timestamp, abs(a.x - b.benchmark)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.