Home > Net >  How to count every entries for each day in PostgreSQL
How to count every entries for each day in PostgreSQL

Time:09-28

I currently have a query that formats bigint values into dates like this "01-01-1970".

My results look like this :

date    
28-01-2021
14-07-2021
15-08-2021
14-07-2021
....

I have duplicate dates in my result, and what I need is to get something like this (and ordered by date descending):

   count    date    
    1        28-01-2021
    2        14-07-2021
    1        15-08-2021
    ....

I tried this :

  SELECT count(to_char(to_timestamp(last_downloaded/1000),
  'DD-MM-YYYY')), to_char(to_timestamp(last_downloaded/1000) from stats;

But it does not give me what I want..

CodePudding user response:

Just use group by. However as @jarlh noted you have to first convert the strings to date or - better - store data as the native type and not as formatted text..

with t(d) as
(
 values
 ('28-01-2021'),
 ('14-07-2021'),
 ('15-08-2021'),
 ('14-07-2021')
)
select to_date(d, 'dd-mm-yyyy'), count(1)
from t
group by 1
order by 1 desc;

In case your bigint values are epoch timestamps in milliseconds then

with t(dts) as
(
 values
 (1632837719969),
 (1632837719969),
 (1632700800123),
 (1632614400234),
 (1630330448696)
)
select to_timestamp(dts/1000)::date, count(1)
from t
group by 1 order by 1 desc;

Result:

to_timestamp count
2021-09-28 2
2021-09-27 1
2021-09-26 1
2021-08-30 1
  • Related