简体   繁体   English

PostgreSQL - 从日期列获取不同年份的计数

[英]PostgreSQL - get count of distinct years from date column

I've got a PostgreSQL table with hundreds of rows, each row containing a value in the column date_creation (type date).我有一个包含数百行的 PostgreSQL 表,每行包含date_creation列中的一个值(类型 date)。

The values look as follows:这些值如下所示:

2010-04-26
2008-08-18
2015-11-11
2010-10-20
2010-03-23
2015-04-08

Now, I'd like to find how often each year occurs.现在,我想知道每年发生的频率。

eg in the above example 2010 occurs 3 times, 2015 occurs 2 times, 2008 occurs 1 time例如在上面的例子中,2010 发生了 3 次,2015 发生了 2 次,2008 发生了 1 次

The first part, how to get distinct years from the date, works fine:第一部分,如何从日期获得不同的年份,工作正常:

SELECT
DISTINCT DATE_PART('year', CAST(date_creation AS DATE)) AS years_available
FROM metadata
WHERE date_creation is not NULL

But I cannot figure out how to also get how often a year occurs.但我无法弄清楚如何获得一年发生的频率。

I've found various answers on here that use COUNT, and although they seem logical at first, none of them will return anything useful.我在这里找到了使用 COUNT 的各种答案,虽然它们一开始看起来很合乎逻辑,但它们都不会返回任何有用的东西。 I assume it is linked to the query including a DISTINCT statement.我假设它链接到包括 DISTINCT 语句的查询。

Use aggregation:使用聚合:

SELECT DATE_PART('year', date_creation::date) AS year, count(*)
FROM metadata
WHERE date_creation is not NULL
GROUP BY year;

Of course, if this is a string, string operations are simpler:当然,如果这是一个字符串,字符串操作就更简单了:

SELECT LEFT(date_creation, 4) as year, COUNT(*)
FROM metadata
WHERE date_creation is not NULL
GROUP BY year;

Use aggregation:使用聚合:

select extract(year from date_creation), count(*) cnt
from metadata
where date_creation is not null
group by 1

Note that there is no need to cast to a date , since you explained that the value has the proper datatype already.请注意,不需要强制转换为date ,因为您已经解释过该值已经具有正确的数据类型。

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

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