Getting Hourly statistics using SQL

ぐ巨炮叔叔 提交于 2019-12-05 21:04:21
Jonathan Leffler

This is closely related to, but slightly different from, this question about How to get the latest record for each day when there are multiple entries per day. (One point in common with many, many SQL questions - the table name was not given originally!)

The basic technique will be to find a function that will format the varied Registered_on values such that all the entries in a particular hour are grouped together. This presumably can be done with TO_CHAR() since we're dealing with Oracle (MySQL does not support this).

SELECT TO_CHAR(Registered_on, "YYYY-MM-DD HH24") AS TimeSlot,
       COUNT(*) AS Registrations
    FROM EmployeeReg
    GROUP BY 1
    ORDER BY 1;

You might be able to replace the '1' entries by TimeSlot, or by the TO_CHAR() expression; however, for reasons of backwards compatibility, it is likely that this will work as written (but I cannot verify that for you on Oracle - an equivalent works OK on IBM Informix Dynamic Server using EXTEND(Registered_on, YEAR TO HOUR) in place of TO_CHAR()).

If you then decide you want zeroes to appear for hours when there are no entries, then you will need to create a list of all the hours you do want reported, and you will need to do a LEFT OUTER JOIN of that list with the result from this query. The hard part is generating the correct list - different DBMS have different ways of doing it.

M.N

Achieved what I wanted, with :)

SELECT TO_CHAR(a.registered_on, 'DD-MON-YYYY HH24') AS TimeSlot,
       COUNT(*) AS Registrations
    FROM EmployeeReg a
    Group By TO_CHAR(a.registered_on, 'DD-MON-YYYY HH24');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!