/*
 * Title  : ash_pga_sql.sql
 * Author : EXADIME LLC
 * Created: 06-Jul-2017
 * Updated: 06-Jul-2017
 * Release: 1.0.0
 * Purpose: Shows details of top PGA consuming SQLs captured in ASH.
 * 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 rownum		format 9999		heading "#"
column sql_id		format a15		heading "SQL Id"
column percent		format 9999		heading "%|Used"
column pga		format 999,999,999,999	heading "Bytes|PGA"

accept p_top	prompt "Enter top rows [10]: " default 10
accept p_min	prompt "Last minutes [60] : " default 60

spool &&rpt_dir/ash_pga_sql.rpt

select 
	rownum,
	sql_id,
	pga,
	percent
from (
	select 
		sql_id,
		sum(delta_pga) pga,
		(ratio_to_report(sum(delta_pga)) over ())*100 percent,rank() over(order by sum(delta_pga) desc) rank
	from (
		select 
			session_id,
			session_serial#,
			sample_id,
			sql_id,
			sample_time,
			is_sqlid_current,
			sql_child_number,
			pga_allocated,
			greatest(pga_allocated - first_value(pga_allocated) over (partition by session_id,session_serial# order by sample_time rows 1 preceding),0) delta_pga
		from
			v$active_session_history
		where
			is_sqlid_current='Y'
		and 
			sample_time > sysdate-&p_min/1440
		order by 
			1,2,3,4
	)
	group by 
		sql_id
	having 
		sum(delta_pga) > 0
)
where 
	rank < (&p_top+1)
and	sql_id is not null
order by 
	rank
/

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