如何按查询分组"correlate"列?

How to "correlate" columns in group by query?

说输入:

Table T1

row_num_unimportant   indicator
        1                 111
        2                 222

Table T2

row_num_unimportant   indicator   val_timestamp   val_of_interest2
        1                 112       timestamp2        value1
        2                 113       timestamp1        value3
        3                 114       timestamp3        value2
        4                 223       timestamp4        value5
        5                 224       timestamp5        value4

我想查看 JOIN 结果

indicator    min_timestamp    val_of_interest2
   111         timestamp1          value3
   222         timestamp4          value5

困难在于val_of_interest2与min_timestamp相关联。

在天真的 JOIN 中说:

SELECT
  indicator,
  MIN(val_timestamp) AS min_timestamp,
  ???? AS val_of_interest2
FROM (
  SELECT
    t1.indicator,
    t2.val_timestamp,
    t2.val_of_interest2
  FROM
    T1 t1
    JOIN T2 t2
    ON (t2.indicator >= t1.indicator)
)
GROUP BY
  indicator

基本上,我在 ???部分? (或者我需要一个不同的查询吗?)

谢谢!

您不会为此使用 group by。一种选择是 window 函数:

SELECT indicator, val_timestamp, val_of_interest2
FROM (SELECT t1.indicator, t2.val_timestamp, t2.val_of_interest2,
             ROW_NUMBER() OVER (PARTITION BY t1.indicator ORDER BY t2.val_timestamp) as seqnum
      FROM T1 t1 JOIN
           T2 t2
           ON t2.indicator >= t1.indicator
     ) t
WHERE seqnum = 1;