简体   繁体   中英

Get weekly totals from database of daily events in SQL

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     |

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.

Quote from the manual

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM