I've got a table storing user access/view logs for the webservice I run. It tracks the time as a timestamp though I'm finding when I do aggregate reporting I only care about the day, not the time.

I'm currently running the following query:

SELECTuser_logs.timestampFROMuser_logsWHEREuser_logs.timestamp >= %(timestamp_1)sAND user_logs.timestamp <= %(timestamp_2)sORDER BYuser_logs.timestamp

There are often other where conditions but they shouldn't matter to the question. I'm using Postgres but I'd assume whatever feature is used will work in other languages.

I pull the results into a Python script which counts the number of views per date but it'd make much more sense to me if the database could group and count for me.

How do I strip it down so it'll group by the day and ignore the time?

1

Best Answer


SELECT date_trunc('day', user_logs.timestamp) "day", count(*) viewsFROM user_logsWHERE user_logs.timestamp >= %(timestamp_1)sAND user_logs.timestamp <= %(timestamp_2)sgroup by 1ORDER BY 1