简体   繁体   中英

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).

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

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. I assume it is linked to the query including a DISTINCT statement.

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.

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