在 PostgreSQL 13 中,我有一个 table_a,其中每个时间戳都有许多行和列。我试图找到 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;```