oracle 如何根据具有多个可能结果的组选择最后一次修改?[关闭]

webghufk  于 2023-04-20  发布在  Oracle
关注(0)|答案(1)|浏览(92)

已关闭,该问题需要details or clarity,目前不接受回答。
**想要改进此问题?**通过editing this post添加详细信息并澄清问题。

7天前关闭
Improve this question
我正试图弄清楚如何使查询仅在对象基于时间戳触及特定系统位置时才显示我。例如:

Query:
SELECT
    id,
    timestamp,
    lp,
    location
FROM
    unit_location
WHERE
    lp IN (
        '1234',
        '9999');

id          timestamp           lp      location
11110000    11-APR-23 15:05:31  1234    Location 2
22220000    11-APR-23 15:22:52  1234    Location 1
33330000    11-APR-23 15:35:10  1234    Location 2
44440000    11-APR-23 15:04:11  9999    Location 2
55550000    11-APR-23 19:29:04  9999    Location 1
66660000    11-APR-23 19:40:14  9999    Location 2

我该如何使查询可以运行,并且它只会带回最后一个timestamp的数据,但前提是每个lp的位置为2?
例如,它只显示ID:

id          timestamp           lp      location
33330000    11-APR-23 15:35:10  1234    Location 2
66660000    11-APR-23 19:40:14  9999    Location 2

我试着在时间戳上使用MAX,基于一些where critera和其他一些小比特和 bat ,但无法复制我需要的结果。

6rvt4ljy

6rvt4ljy1#

有多种可能性,你正在尝试做什么。这里有两个变体的查询使用窗口函数;他们对待领带的方式不同。
MAX

SELECT id, timestamp, lp, location
FROM (SELECT unit_location.*, MAX(timestamp) OVER (PARTITION BY lp) AS last_timestamp
FROM unit_location
) ul
WHERE timestamp = last_timestamp

关于ROW_NUMBER

SELECT id, timestamp, lp, location
FROM (SELECT unit_location.*, ROW_NUMBER() OVER (PARTITION BY lp ORDER BY timestamp DESC) AS timestamp_number
FROM unit_location
) ul
WHERE timestamp_number = 1

下面是一个MAXaggregate的版本:

SELECT id, timestamp, unit_location.lp, location
FROM unit_location
JOIN (SELECT lp, MAX(timestamp) AS max_timestamp FROM unit_location GROUP BY lp) ul
    ON unit_location.lp = ul.lp AND timestamp = max_timestamp

您可以选择开销最小的查询和/或您最了解的查询。

相关问题