Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: SQL Server
Expertise: Beginner
Mar 25, 1997



Application Security Testing: An Integral Part of DevOps

Calculating Averages Using Clock Times

Joe Celko's Store Survey Puzzle]

You are collecting statistical information stored by the quarter hour. What your customer wants is to get information by hour — not on the hour. That is, we don't want to know what the load was at 00:00 Hrs, at 01:00 Hrs, at 02:00 Hrs, and so forth. We want the average load for the first four quarter hours (00:00, 00:15, 00:30, 01:00), for the next four quarter hours (00:15, 00:30, 01:00, 01:15) and so forth. The sample table looks like this:

        (calendar DATE NOT NULL, 
        clock TIME NOT NULL, 
        load REAL NOT NULL,
        PRIMARY KEY(calendar, clock));

The best way is to add another column to hold the reporting period:

        (calendar DATE NOT NULL, 
        clock TIME NOT NULL, 
        period INTEGER DEFAULT (0) CHECK (period BETWEEN 0 AND 96),
        load REAL DEFAULT (0) NOT NULL,
        PRIMARY KEY (calendar, clock));
Then update the table with a series of statements like this:
    UPDATE LoadData
        SET period = 0
        WHERE clock IN (00:00, 00:15, 00:30, 01:00);
Now the report becomes:
    SELECT period, MAX(clock), AVG(load)
        FROM LoadData
        GROUP BY period;
If you are not sure that the samples will fall exactly on the quarter hour then hedge your bets a little bit by letting the clock times fall within a time frame.
    UPDATE LoadData
        SET period = 1
        WHERE clock BETWEEN 00:00 AND 01:00;
Just how you want to handle the query is up to you. The first query will still work, but it does not allow for the spacing of the samples should they be too close together.

Puzzle provided courtesy of:
Joe Celko

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date