- workflow
$ heroku pg:psql -a isis-db
\d
\d+
SELECT * from agents;
\d expenses
\set ECHO_HIDDEN on \d
\set ECHO_HIDDEN off
SELECT * from expenses LIMIT 1;
\e SELECT * from expenses JOIN agents on agent_uuid = agents.uuid LIMIT 1;
\x SELECT * from expenses JOIN agents on agent_uuid = agents.uuid LIMIT 1;
\x auto
we're going to generate random status reports from our agents, who they are, what they're doing and when.
SELECT ARRAY['training','idle','assigned','captured','recovering'];
SELECT (ARRAY['training','idle','assigned','captured','recovering'])[random() * 4 + 1];
SELECT now();
SELECT now() - '1 year ago'::interval;
SELECT now() - '1 year ago'::interval * random();
SELECT (SELECT uuid FROM agents ORDER BY random() LIMIT 1);
SELECT (SELECT uuid FROM agents ORDER BY random() LIMIT 1) as agent_uuid, (ARRAY['training','idle','assigned','captured','recovering'])[random() * 4 + 1] as state, now() - '1 year ago'::interval * random() as time FROM generate_series(1, 10)
SELECT (SELECT uuid FROM agents ORDER BY random()+g*0 LIMIT 1) as agent_uuid, (ARRAY['training','idle','assigned','captured','recovering'])[random() * 4 + 1] as state, now() - '1 year ago'::interval * random() as time FROM generate_series(1, 10) as g
CREATE TABLE agent_statuses AS (SELECT (SELECT uuid FROM agents ORDER BY random()+g*0 LIMIT 1) as agent_uuid, (ARRAY['training','idle','assigned','captured','recovering'])[random() * 4 + 1] as state, now() - '1 year ago'::interval * random() as time FROM generate_series(1, 1000) as g);
SELECT * from agent_statuses ORDER BY agent_uuid, time;
i wonder which agents got captured while they were in training? this is going to need a WINDOW FUNCTION
SELECT *, lead(state, 1) OVER (partition by agent_uuid order by time) as next from agent_statuses;
WITH status_with_next AS ( SELECT *, lead(state, 1) OVER (partition by agent_uuid order by time) as next from agent_statuses ) SELECT * from status_with_next WHERE state = 'training' and next = 'captured';
WITH status_with_next AS ( SELECT , lead(state, 1) OVER (partition by agent_uuid order by time) as next from agent_statuses ), oops AS ( SELECT * from super_status WHERE state = 'training' and next = 'captured' ) SELECT name, count() as training_captures from oops join agents on agents.uuid = agent_uuid GROUP BY name ORDER by training_captures DESC;