0

Recently I wanna make a sql query on PostgreSQL that can do a counting of a table records that of everyday (or maybe every hour) of a certain period (a month or a day etc).

A loop through every day of a period (month), in other words.

How can I do this?

I wish the record could be something similar to this:

--------------------
count | day | month |
1     | 1   |  4    |
1     | 2   |  4    |
1     | 3   |  4    |
1     | 4   |  4    |
1     | 5   |  4    |

Update:

I have a table called visitors:

first_seen:date_time; last_seen: date time; id: integer

I wanna calculate total visitor of every day of a month. But since a visitor can be shown up more than multiple day a time, i.e stayed for 3 days. I found a simple count(id) wont do the trick.

Update 2:

This is what i did so far, but apparently wrong.

SELECT count("visitors"."id"), 

EXTRACT(hour from visitors.last_seen) AS hour, 
EXTRACT(day from "visitors"."last_seen") AS date, 
EXTRACT(month from "visitors"."last_seen") AS month 

FROM "visitors"
WHERE (("visitors"."first_seen" between '2014-04-09 15:30:07.423401' and '2014-04-10 15:30:07.423476') 
or ("visitors"."last_seen" between '2014-04-09 15:30:07.423401' and  '2014-04-10 15:30:07.423476') 
or ("visitors"."first_seen" < '2014-04-09 15:30:07.423401' and "visotors".last_seen > '2014-04-10 15:30:07.423476')) 

GROUP BY month,date,hour ORDER BY month asc, date asc , hour asc

Sorry for the lack of informations.

3
  • What does the initial data set look like? Commented Apr 11, 2014 at 14:09
  • What does the schema look like? What have you tried so far? Commented Apr 11, 2014 at 14:09
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. Please provide the query that you've attempted and sample data. Commented Apr 11, 2014 at 14:09

2 Answers 2

2

You can use generate_series fill the gap data when vistor spead the statistic perids. and then group it. for exp :

select count(id),
EXTRACT(hour from visitors.last_seen) AS hour, 
EXTRACT(day from "visitors"."last_seen") AS date, 
EXTRACT(month from "visitors"."last_seen") AS month 
from
(select id,generate_series(first_seen,last_seen,'1 hour'::interval) from tbl) t
where ...
GROUP BY month,date,hour 

ORDER BY month asc, date asc , hour asc
Sign up to request clarification or add additional context in comments.

Comments

0

Use the DATE_TRUNC function.

SELECT count(id),
       date_trunc('day', last_seen) AS DATE
 FROM visitors
  GROUP BY date_trunc('day', last_seen);

1 Comment

This is counting all IDs by day regardless the user logged in multiple times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.