sql—如何按查询“关联”分组中的列?

rkue9o1l  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(365)

说输入:
表t1

row_num_unimportant   indicator
        1                 111
        2                 222

表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

我想看看结果

indicator    min_timestamp    val_of_interest2
   111         timestamp1          value3
   222         timestamp4          value5

困难在于有兴趣值2与最小时间戳相关。
天真地说:

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

基本上,我应该把什么放在???部分(或者我需要一个不同的查询吗?)
谢谢!

ygya80vv

ygya80vv1#

你不会用 group by 为了这个。一个选项是窗口功能:

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;

相关问题