Consider the following event data in PostgreSQL 9.4:
eventTime | eventName
2015-09-25 18:00:00 | 'AAA'
2015-09-25 17:00:00 | 'BBB'
2015-09-25 16:00:00 | 'BBB'
2015-09-25 15:00:00 | 'BBB'
2015-09-25 14:00:00 | 'AAA'
2015-09-26 13:00:00 | 'CCC'
2015-09-26 12:00:00 | 'AAA'
2015-09-26 11:00:00 | 'BBB'
2015-09-26 10:00:00 | 'CCC'
2015-09-26 09:00:00 | 'BBB'
2015-09-27 08:00:00 | 'AAA'
2015-09-27 07:00:00 | 'CCC'
2015-09-27 05:00:00 | 'CCC'
2015-09-27 04:00:00 | 'CCC'
2015-09-27 03:00:00 | 'CCC'
2015-09-27 02:00:00 | 'AAA'
While single count()
based tables are straightforward, for example:
SELECT eventTime, count(1)
from (SELECT data->>'eventName' as eventName,
date_trunc('day', to_timestamp(data->>'timestamp','YYYY-MM-DDZHH24:MI:SS.MS')::timestamp without time zone) AS eventTime
FROM sidetrack where (data->>'eventName' = 'AAA') IS TRUE) AS tmptab
GROUP BY eventTime
ORDER BY eventTime ASC
It's only possible to count the occurrence of a single value of eventName
. I'm not very experienced with SQL and am struggling to find a way to create a two-way frequency table. In this example the result would be:
day | 'AAA' | 'BBB' | 'CCC'
------------+-------+-------+-------
2015-09-25 | 2 | 3 | 0
2015-09-26 | 1 | 2 | 2
2015-09-27 | 2 | 0 | 4
There are examples where variables with numeric values are counted
using with_bucket()
, but that doesn't generalize to string valued fields.
I've tried nested selects under WITH
, such as:
WITH
foo AS (
SELECT ...
),
bar AS (
SELECT ...
FROM foo
),
SELECT *
FROM bar;
And with outer JOINS, but I can't crack this.