Reputation: 61
I have a database of events linked to individual users (let's call them A, B, C), and listed by timestamp with timezone.
I need to put together a SQL query that tells me the total number of events from A, B, and C by week.
How would I do this?
Example Data:
| "UID" | "USER" | "EVENT" | "TIMESTAMP" |
| 1 | 'A' | "FLIGHT" | '2015-01-06 08:00:00-05' |
| 2 | 'B' | "FLIGHT" | '2015-01-07 09:00:00-05' |
| 3 | 'A' | "FLIGHT" | '2015-01-08 11:00:00-05' |
| 4 | 'A' | "FLIGHT" | '2015-01-08 12:00:00-05' |
| 5 | 'C' | "FLIGHT" | '2015-01-13 06:00:00-05' |
| 6 | 'C' | "FLIGHT" | '2015-01-14 09:00:00-05' |
| 7 | 'A' | "FLIGHT" | '2015-01-14 10:00:00-05' |
| 8 | 'A' | "FLIGHT" | '2015-01-06 12:00:00-05' |
Desired Output:
| Week | USER | FREQUENCY |
| 1 | A | 3 |
| 1 | B | 1 |
| 2 | A | 2 |
| 2 | C | 2 |
Upvotes: 0
Views: 336
Reputation:
Looks like a simple aggregation to me:
select extract(week from "TIMESTAMP") as week,
"USER",
count(*)
from the_table
group by extract(week from "TIMESTAMP"), "USER"
order by extract(week from "TIMESTAMP"), "USER";
extract(week from ...)
uses the ISO definition of the week.
In the ISO week-numbering system, it is possible for early-January dates to be part of the 52nd or 53rd week of the previous year, and for late-December dates to be part of the first week of the next year
So it's better to use a display that includes the week and the year. This can be done using to_char()
select to_char("TIMESTAMP", 'iyyy-iw') as week,
"USER",
count(*)
from the_table
group by to_char("TIMESTAMP", 'iyyy-iw'), "USER"
order by to_char("TIMESTAMP", 'iyyy-iw'), "USER";
If you want to limit that to specific month you can add the appropriate where
condition.
Upvotes: 1