@@header

/*
*
*  Author     : Vishal Gupta
*  Purpose    : Display top user from ASH
*  Parameters : 1 - Number of MINUTES (Default 5min))
*               2 - Top Row Count      Default 10)
*
*  Revision History:
*  ===================
*  Date       Author        Description
*  ---------  ------------  -----------------------------------------
*  02-Apr-13  Vishal Gupta  Created
*
*/


/************************************
*  INPUT PARAMETERS
************************************/
UNDEFINE MINUTES
UNDEFINE TOPROWCOUNT
UNDEFINE INST_ID

DEFINE MINUTES="&&1"
DEFINE TOPROWCOUNT="&&2"
DEFINE INST_ID='&&3'


set term off
COLUMN  _MINUTES         NEW_VALUE  MINUTES           NOPRINT
COLUMN  _TOPROWCOUNT     NEW_VALUE  TOPROWCOUNT       NOPRINT
COLUMN  _INST_ID         NEW_VALUE  INST_ID           NOPRINT

SELECT DECODE('&&MINUTES','','5','&&MINUTES')         "_MINUTES" 
     , DECODE('&&TOPROWCOUNT','','5','&&TOPROWCOUNT') "_TOPROWCOUNT" 
     , DECODE('&&INST_ID','','%','&&INST_ID') "_INST_ID" 
from dual;   

set term on

PROMPT *****************************************************************
PROMPT * ASH - Top &&TOPROWCOUNT Active Clients (Over Last &&MINUTES min)
PROMPT * 
PROMPT * Input Parameters 
PROMPT *  - Minutes       = '&&MINUTES' 
PROMPT *  - Top Row Count = '&&TOPROWCOUNT' 
PROMPT *  - Instance ID   = '&&INST_ID' 
PROMPT *****************************************************************


COLUMN  client_id         HEADING "Client ID"              FORMAT a40
COLUMN  percent           HEADING "Activity| (%age)"       FORMAT 999.99
COLUMN  session_count     HEADING "Active|Session|Count"   FORMAT 999,999

WITH ash as
    (SELECT /*+ NO_MERGE */
            ash.client_id
          , count(1) session_count
      FROM gv$active_session_history ash
     WHERE ash.sample_time > systimestamp - (&&MINUTES/(24*60))
    AND ash.session_type <> 'BACKGROUND'
       AND ash.inst_id LIKE '&&INST_ID'
     GROUP BY ash.client_id
    )
, ash_total  as
   (SELECT /*+ NO_MERGE */ SUM(session_count) session_total   
      FROM ash  
   )
SELECT * FROM (   
SELECT ash.client_id
     , LPAD(TO_CHAR(ROUND((session_count/ash_total.session_total)* 100,2),'999.99'),6) percent
     , ash.session_count
  FROM ash , ash_total
 ORDER BY ROUND((session_count/ash_total.session_total)* 100,2) desc
 )
 WHERE ROWNUM <= &&TOPROWCOUNT
; 


@@footer
