/*
 * Title  : awr_sys_hist.sql
 * Author : EXADIME LLC
 * Created: 20-Apr-2021
 * Updated: 20-Apr-2021
 * Release: 1.0.0
 * Purpose: Shows sysmetric history captured in awr.
 * History: N/A
 */

start oracle.ini

set echo off
set feedback off
set serverout on
set termout on

set linesize 100
set pagesize 0
set pause off
set long 80

set heading on
set headsep on
set underline on
set colsep " "

set define on
set verify off
set escape off
set embedded on

column sno              format 9999             heading "#"               
column snid             format 999999           heading "SnapId"
column time             format a15              heading "Begin Time"
column name             format a45              heading "Name"
column aval             format 99,999,999       heading "Average"
column mval             format 99,999,999       heading "Maximum"

select distinct metric_name from dba_hist_sysmetric_history order by 1;

accept p_bsnap	prompt "Enter Begin Snap Id: "
accept p_esnap	prompt "Enter End Snap Id: "
accept p_name   prompt "Enter Metric Name:" 
accept p_inst char prompt "Enter instance number: " default 1
accept p_order	prompt "Enter sort order [asc|desc]: " default snap_id

spool &&rpt_dir/awr_sys_hist.rpt

select
	row_number() over(order by &&p_order)			sno,
	snap_id                                                 snid,
	to_char(begin_interval_time,'yyyymmdd hh24:mi')         time,
	metric_name                                             name,
	avalue                                                  aval,
	mvalue                                                  mval
from 
	(
		select 
			s.snap_id,
			s.begin_interval_time,
			t.metric_name,
			avg(value) avalue,
			max(value) mvalue
		from 
			dba_hist_snapshot s, dba_hist_sysmetric_history t
		where
			s.snap_id = t.snap_id
		and	s.instance_number = t.instance_number 
		and	s.dbid = t.dbid
		and	s.instance_number = (select instance_number from v$instance)
		and	s.dbid = (select dbid from v$database)
		and	t.metric_name = '&&p_name'
		and	s.snap_id between &p_bsnap and &p_esnap
		and     s.instance_number=&&p_inst
		group by
			s.snap_id,
			s.begin_interval_time,
			t.metric_name
		order by
			s.snap_id desc
) order by
	&&p_order
/

spool off

clear columns

set embedded off
set escape off
set verify on
set define on

set colsep " "
set underline on
set headsep on
set heading on

set pause off
set pagesize 24
set linesize 80
set long 80

set termout on
set serverout off
set feedback on
set echo off