简体   繁体   English

在SQL中从每日事件数据库中获取每周总计

[英]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. 我有一个链接到各个用户的事件数据库(我们称它们为A,B,C),并按带有时区的时间戳列出。

I need to put together a SQL query that tells me the total number of events from A, B, and C by week. 我需要组合一个SQL查询,该查询按周告诉我来自A,B和C的事件总数。

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. extract(week from ...)使用extract(week from ...)ISO定义

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 在ISO周编号系统中,一月初的日期可能是上一年的第52或53周的一部分,而十二月末的日期可能是下一年的第一周的一部分

So it's better to use a display that includes the week and the year. 因此,最好使用包含星期年份的显示。 This can be done using to_char() 这可以使用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. 如果要将其限制为特定月份,可以添加适当的where条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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