在SQL(postgresql)中如何基于“没有时区的时间戳”列进行分组?

dpiehjr4  于 5个月前  发布在  PostgreSQL
关注(0)|答案(4)|浏览(74)

我正在尝试写一些查询,以在postgresql中基于每个月对事物进行分组。
假设我们有一个表“crimes”,其中有2列“activity date”(没有时区的时间戳)和“zipcode”(字符变化(5)),如何查询给定zipcode的每个月的犯罪数量?
例如:表“罪行”:

activity date               zipcode
2014-11-22 00:52:00           12345
2014-10-22 00:52:00           12345
2014-10-24 00:52:00           12345
2014-12-22 00:52:00           54321

字符串
输入:给定邮政编码“12345”
输出:返回

month        count
2014-10        2
2014-11        1

qyyhg6bp

qyyhg6bp1#

试试看:

select
    extract(year from activity_date) as year,
    to_char(activity_date, 'Mon') as month,
    count(*) as count
from
    crimes
group by
    1,extract(month from activity_date);

字符串

z18hc3ub

z18hc3ub2#

如何在PostgreSQL中从时间戳(带/不带时区)中获取月份?

使用函数EXTRACT(字段FROM source)

SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 2

字符串
文档链接:https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT

0h4hbjxa

0h4hbjxa3#

我喜欢用途:

SELECT DATE_TRUNC('month', activity_date AT TIME ZONE 'UTC') AS month

字符串
那么结果会是这样的:

month                              count
2023-10-01 00:00:00.000              1
2023-11-01 00:00:00.000              2


如果你想用week来计数,你可以把它改成:

SELECT DATE_TRUNC('week', activity_date AT TIME ZONE 'UTC') AS week


或按year计数:

SELECT DATE_TRUNC('year', activity_date AT TIME ZONE 'UTC') AS year


但是如果你想按date计数,上面的SQL是不起作用的,请坚持:

SELECT DATE(conversation.created_date) AS day

sycxhyv7

sycxhyv74#

Declare @zipcode int;
set @zipcode=12345;
select format(activity_date,'yyyy-MM') month ,count(1) count from ct
where zipcode=@zipcode
group by format(ad,'yyyy-MM')

字符串

相关问题