【问题标题】:DB2 MAX with additional columns带有附加列的 DB2 MAX
【发布时间】: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

【问题讨论】:

标签: sql select db2 max report


【解决方案1】:

我不明白您的查询与数据之间的关系。但是对于您的要求,请使用row_number()rank()

select s.*
from (select s.*,
             row_number() over (partition by entity order by bytes desc, start_time desc) as seqnum
      from summary s
      where . . .
     ) s
where seqnum = 1;

【讨论】:

  • 该表基本上是所有备份的日志,我们希望找到每个服务器在一个月内最大的备份,并且需要日期和会话#以及备份的数量。我的假设是,他们想查看某些服务器是否在每个月的特定日期执行月度工作,而服务器所有者没有通知我们。这些数据可能会帮助我们调整备份开始时间,以便在这些工作发生时它们不会运行很长时间。我可以将表格转储到 excel 中,并在 excel 中轻松地做到这一点,但我认为 DB2 应该能够同样轻松地做到这一点。
  • @GordonLinoff 您应该在over 的末尾添加, START_TIME desc 以满足要求:If there is a duplicate I want the most recent record
  • @MarkBarinstein 。 . .谢谢。
  • 这似乎是稍加修改的答案。我给你的表是一个更大表中列的子集。我应该澄清一下……我的错。一旦我拿到你的脚本并运行它,我就确定了如何只返回我需要的列,并且能够返回我需要的数据。
猜你喜欢
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
相关资源
最近更新 更多