【问题标题】:Aggregate Records by Month按月汇总记录
【发布时间】:2021-02-16 14:46:49
【问题描述】:

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

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

期望的输出

【问题讨论】:

    标签: sql oracle datetime average aggregate-functions


    【解决方案1】:

    您通常会使用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)
    

    【讨论】:

    • 非常感谢您抽出宝贵时间。这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多