【发布时间】:2020-04-03 16:38:02
【问题描述】:
我有一个 DB2 表,其中包含我需要在查询中返回的以下列
ENTITY START_TIME END_TIME NUMBER BYTES
SERVER1SQL 2020-03-29 23:03:04 2020-03-30 01:52:37 761102 72212891243
SERVER1 2020-03-31 00:00:30 2020-03-31 01:33:40 765443 4532123432
SERVER2 2020-03-31 01:00:10 2020-03-31 01:40:12 765831 19531321013
SERVER19 2020-03-31 00:20:30 2020-03-31 02:10:40 765955 5212347991
SERVER7 2020-03-31 02:00:29 2020-03-31 02:33:10 766121 2321956753
SERVER1SQL 2020-03-30 23:00:50 2020-03-31 03:40:18 764892 72212891243
SERVER11 2020-03-31 03:06:02 2020-03-31 04:05:40 766337 688174321
我需要为每个实体找到最大(字节)的记录,但需要返回所有列。我的问题是我的数据库实体将日复一日地备份相同的数量,如果我想返回 30 天并找到特定实体返回多条记录的最大字节数。只有当我只包含 ENTITY 和 MAX(BYTES) 而没有日期和数字(即 SESSION ID)时,该查询似乎才有效。那么如何在没有重复的情况下获得 MAX 结果。如果有重复我想要最近的记录。这是我目前拥有的主要作品减去返回重复项的数据库实体。搜遍了,这种查询好像有问题。
select
varchar(max_sum.entity,45) as entity,
translate('abcde fg:hi:jk', a.start_time, '_____abcde_fg_hi_jk_____',' ') AS start_time,
translate('abcde fg:hi:jk', a.end_time, '_____abcde_fg_hi_jk_____',' ') AS end_time,
a.number,
max_sum.max_MB
from (select varchar(entity,45) as entity, MAX(bytes/1024/1024) as max_MB
from summary
where activity='BACKUP'
and
start_time>=(current_timestamp 7 days)
and
entity is not NULL
group by entity) as max_sum, summary a
where a.entity=max_sum.entity
and
(a.bytes/1024/1024)=max_sum.max_MB
and
a.activity='BACKUP'
and
a.start_time>=(current_timestamp 7 days)
and
a.entity is not NULL
order by max_sum.entity
【问题讨论】:
-
这能回答你的问题吗? Select first row in each GROUP BY group? 这似乎是greatest-n-per-group 查询的一种形式。