如何基于一列限制行?

zsohkypk  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(398)

我有一个表,其中包含osi#key(identification#)、value和time列。我想知道每一个osi\ U密钥何时达到其最大值。我编写了一个sql查询,可以执行以下操作:

SELECT t1.osi_key, t1.time, t1.value
FROM
(
SELECT osi_key, MAX(value) AS max_value
FROM data_values_6_2020
WHERE value > 0
GROUP BY osi_key
) AS t2
INNER JOIN data_values_6_2020 AS t1
ON t1.osi_key = t2.osi_key
AND t1.value = t2.max_value

例子
但是,如果它看到同一osi\ U键的最大值重复,它将返回具有唯一时间戳的所有行。
例1
我想它忽略多个时间戳,只返回一行为每个osi\ U键。也许最新的时间戳是这样的:
例2
这可能吗?

1szpjjfi

1szpjjfi1#

如果数据库支持,则可以使用窗口函数:

select osi_key, time, value
from (
    select 
        d.*, 
        row_number() over(partition by osi_key order by value desc, time desc) rn
    from data_values_6_2020 d
) t
where rn = 1
lsmepo6l

lsmepo6l2#

执行t1.time的最大值:

SELECT t1.osi_key, MAX(t1.time), t1.value FROM ( SELECT osi_key, MAX(value)
AS max_value FROM data_values_6_2020 WHERE value > 0 GROUP BY osi_key ) AS t2
INNER JOIN data_values_6_2020 AS t1 ON t1.osi_key = t2.osi_key AND t1.value =
t2.max_value
GROUP BY t1.osi_key, t1.osi_key

但由于从同一个表中获取值和数据更简单:

SELECT osi_key, MAX(time) as maxTime, MAX(value) as maxValue from data_values_6_2020
group by osi_key

相关问题