DROP TABLE IF EXISTS pg_stat_statements_temp; create table pg_stat_statements_temp as SELECT d.datname,u.usename, s.queryid, round(s.total_time::numeric, 2) AS total_time, s.calls, round(s.mean_time::numeric, 2) AS mean, now() as cur_date FROM pg_stat_statements s join pg_database d on s.dbid=d.oid join pg_user u on s.userid=u.usesysid; select pg_sleep(15); with stat as (SELECT d.datname,u.usename, s.queryid,s.query, round(s.total_time::numeric, 2) AS total_time, s.calls, round(s.mean_time::numeric, 2) AS mean FROM pg_stat_statements s join pg_database d on s.dbid=d.oid join pg_user u on s.userid=u.usesysid ) select s.datname,s.usename,s.queryid,regexp_replace(s.query, E'[\n\r]+', ' ', 'g' )::varchar(80) AS short_query, s.total_time-t.total_time as time, s.calls-t.calls as calls, s.mean -t.mean as mean, round( (100 * (s.total_time-t.total_time) /sum(s.total_time-t.total_time) OVER () )::numeric, 2) as cpu, now()-t.cur_date as diff_time, CASE WHEN s.calls-t.calls >0 THEN (s.calls-t.calls )/(extract ( second from now()-t.cur_date) + extract ( minutes from now()-t.cur_date)*60 + extract ( minutes from now()-t.cur_date)*60*60 ) else '0' end as tps from stat s join pg_stat_statements_temp t on s.datname=t.datname and s.usename=t.usename and s.queryid=t.queryid order by cpu desc limit 20;