Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform this average count per hour calculation in SQL?

A simplified version of my table looks like this:

id hour
1 3
1 3
1 3
1 4
2 12
2 12
2 14

The hour column means 3am, 4am, 12pm etc. What I’d like to be able to do (working in Amazon Athena) is to calculate the average number of times an id occurs per hour. So for id 1, I’d have 3 occurrences at 3am and 1 at 4am, making my average calculation (3+1)/2 = 2 per hour. My combination of count and group by operators are not getting the job done at the moment.

Output I want:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id average per hour
1 2
2 1.5

>Solution :

You can divide the total count per id by the distinct count of hours:

SELECT   id, COUNT(*) / COUNT(DISTINCT hour)
FROM     mytable
GROUP BY id
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading