按月汇总记录

Aggregate Records by Month

我有一个 table 正在查询,如下所示。 table 每天都有一个记录。我想更新查询,以便每月细分数据(所需输出)。关于如何做到这一点的任何想法?数据库是 Oracle。

select SNAP_TIME, SEG_GB, DB_SIZE, FREE_GB from dbsize
where SNAP_TIME > sysdate -730

期望的输出

您通常会使用 trunc() 和聚合函数。假设您想要每个月的每个值的平均值,那么:

select trunc(snap_time, 'month') snap_month, 
    avg(seg_gb) seg_gb, avg(db_size) db_size, avg(free_gb) free_gb
from dbsize
where snap_time > add_months(sysdate, -12)
group by trunc(snap_time, 'month')
order by snap_month

如果您想要将截断日期实际格式化为 mon-yy,如预期结果所示,请改用 to_char()

select to_char(snap_time, 'mon-yy') snap_month, 
    avg(seg_gb) seg_gb, avg(db_size) db_size, avg(free_gb) free_gb
from dbsize
where snap_time > add_months(sysdate, -12)
group by to_char(snap_time, 'mon-yy')
order by min(snap_time)