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

时间:2016-06-22 13:20:53

标签: sql postgresql

我有一个链接到各个用户的事件数据库(让他们称之为A,B,C),并按时间戳列出时区。

我需要整理一个SQL查询,告诉我每周A,B和C的事件总数。

我该怎么做?

示例数据:

| "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' |

期望的输出:

| Week | USER | FREQUENCY |
|  1   |  A   |     3     |
|  1   |  B   |     1     |
|  2   |  A   |     2     |
|  2   |  C   |     2     |

1 个答案:

答案 0 :(得分:1)

看起来像是一个简单的聚合:

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 ...)使用本周的ISO definition

Quote from the manual

  

在ISO周编号系统中,1月初的日期可能是上一年的第52周或第53周的一部分,12月末的日期可能是明年第一周的一部分。

因此,最好使用包含一周的显示。这可以使用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";

如果要将其限制为特定月份,可以添加适当的where条件。