/*
 * Title  : awr_cpu_hist.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 16-Jun-2023
 * Release: 1.0.0
 * Purpose: CPU 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 "SnapId"
column inst	format 9999		heading "Node"
column time	format a15		heading "Time"
column cpu	format 999		heading "%|CPU"

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 snap_id

spool &&rpt_dir/awr_cpu_hist.rpt

select
	row_number() over(order by &&p_order)			sno,
	snap_id							snid,
	to_char(snaptime,'yyyymmdd hh24:mi')			time,
	round(busydelta / (busydelta + idledelta) * 100, 2)	cpu
from 
	(
		select 
			s.snap_id,
			s.begin_interval_time snaptime,
			os1.value - lag(os1.value) over (order by s.snap_id) busydelta,
			os2.value - lag(os2.value) over (order by s.snap_id) idledelta
		from 
			dba_hist_snapshot s, dba_hist_osstat os1, dba_hist_osstat os2
		where
			s.snap_id = os1.snap_id 
		and	s.snap_id = os2.snap_id
		and	s.instance_number = os1.instance_number 
		and	s.instance_number = os2.instance_number
		and	s.dbid = os1.dbid and s.dbid = os2.dbid
		and	s.instance_number = (select instance_number from v$instance)
		and	s.dbid = (select dbid from v$database)
		and	os1.stat_name = 'BUSY_TIME'
		and	os2.stat_name = 'IDLE_TIME'
		and	s.snap_id between &p_bsnap and &p_esnap
		and     s.instance_number=&&p_inst
		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