Skip to content
Advertisement

Sum of item count in an SQL query based on DATE_TRUNC

I’ve got a table which contains event status data, similar to this:

I’d like to construct a query which returns the number of successful events each day, so:

I’ve stumbled across this SO answer to a similar question, but the answer there is for all the data returned by the query, whereas I need the sum grouped by date range.

Also, I cannot use BETWEEN to select a specific date range, since this query is for a Grafana dashboard, and the date range is determined by the dashboard’s UI. I’m using Postgres for the SQL dialect, in case that matters.

Advertisement

Answer

You need to remove the time from time component. In most databases, you can do this by converting to a date:

This assumes that 1 means “successful”.

The cast() does not work in all databases. Other alternatives are things like trunc(time), date_trunc('day', time), date_trunc(time, day) — and no doubt many others.

In Postgres, I would phrase this as:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement