views:

595

answers:

2

We have a table, name 'employeeReg' with fields

employeeNo | employeeName | Registered_on

Here *Registered_on* is a timestamp.

We require an hourly pattern of registrations, over a period of days. eg.

01 Jan 08 : 12 - 01 PM : 1592 registrations

01 Jan 08 : 01 - 02 PM : 1020 registrations

Can someone please suggest a query for this.


We are using Oracle 10gR2 as our DB server.

+3  A: 

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.

Jonathan Leffler
Hi Jonathan, sorry for missing that. Have given the table name now.
Mohit Nanda
NP: It was a wry observation based on answering a fair number of SQL questions. I've updated the answer appropriately - I've left the 'One point in common' sentence in place, but italicized it, and added 'originally'.
Jonathan Leffler
+1  A: 

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');
Mohit Nanda