/*
 * Title  : awr_inst_hist.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 16-Jun-2023
 * Release: 1.0.0
 * Purpose: Instance usage history captured in awr.
 * History: N/A
 */

start oracle.ini

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

set linesize 125
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 99999		heading "#"
column snid	format 999999		heading "Snap Id"
column inst	format 9999		heading "Node"
column time	format a15		heading "Snap Time"
column sga	format 999,999,999	heading "SGA"
column pga	format 999,999,999	heading "PGA"
column total	format 999,999,999	heading "KBytes|Total"

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

spool &&rpt_dir/awr_inst_hist.rpt

select
	row_number() over(order by &&p_order)		sno,
	snid,
	time,
	inst, 
	sga, 
	pga,
	total
from 
	(
		select
			sn.snap_id						snid,
			to_char(sn.begin_interval_time,'yyyymmdd hh24:mi')	time,
			sn.instance_number					inst, 
			sga.allo						sga, 
			pga.allo						pga,
			(sga.allo+pga.allo)					total
		from
			(
				select 
					snap_id,
					instance_number,
					round(sum(bytes)/1024) allo 
				from 
					dba_hist_sgastat 
				group by 
					snap_id,instance_number
			) sga,
			(
				select 
					snap_id,instance_number,round(sum(value)/1024) allo 
				from 
					dba_hist_pgastat where name = 'total PGA allocated' 
				group by 
					snap_id,instance_number
			) pga,
			dba_hist_snapshot sn 
		where
			sn.snap_id=sga.snap_id
		and	sn.instance_number=sga.instance_number
		and	sn.snap_id=pga.snap_id
		and	sn.instance_number=pga.instance_number
		and	sn.snap_id between &p_bsnap and &p_esnap
		and     sn.instance_number=&&p_inst
		order by 
			sn.snap_id desc,
			sn.instance_number
) 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
