Last active
August 29, 2015 14:09
-
-
Save troyk/3961b259ee430c7a1d76 to your computer and use it in GitHub Desktop.
Don't try this with MongoDB Folks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
with v(dfrom, dto) as ( | |
VALUES('2014-01-01'::date, '2014-11-12'::date) | |
--VALUES(_from, _to) | |
), failures as ( | |
select user_id, 'data-entry'::citext as action, count(*) as "count" from ad_histories, v | |
where action='qc-fail' and created_at>=v.dfrom and created_at<=v.dto | |
and exists(select 1 from ad_histories subq where ad_id=subq.ad_id and subq.action='data-entry' limit 1) group by user_id | |
), elapsed as ( | |
select r.user_id,r.action,avg(r.elapsed) as "avg_time" from ( | |
select user_id,action, lead(created_at,1,now()) over w - created_at as elapsed | |
from ad_histories,v | |
where created_at>=v.dfrom and created_at<=v.dto | |
window w as ( | |
partition by user_id | |
order by created_at | |
) | |
) r group by r.user_id, r.action | |
), counts_by_status as ( | |
select ah.action,count(ah.*) as "count" from ad_histories ah,v | |
where created_at>=v.dfrom and created_at<=v.dto | |
group by ah.action | |
), counts_by_user as ( | |
select ah.user_id,ah.action,count(ah.*) as "count" from ad_histories ah,v | |
where created_at>=v.dfrom and created_at<=v.dto | |
group by ah.user_id,ah.action | |
), counts_with_failures as ( | |
select u.email,c.*, | |
f.count as "failures", | |
(select count from counts_by_status where action=c.action) as "total", | |
((c.count::float/(select count from counts_by_status where action=c.action)::float)*100)::int as "percent_count", | |
((f.count::float/c.count::float)*100)::int as "percent_failures", | |
e.avg_time | |
from counts_by_user c | |
join users u on u.id = c.user_id | |
left join failures f on f.user_id = c.user_id and f.action = c.action | |
left join elapsed e on e.user_id = c.user_id and e.action = c.action | |
) select to_json(counts_with_failures) from counts_with_failures order by email,action; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment