473,395 Members | 1,938 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Average Computation Question

My table is laid out as such:

ID (int) What (varchar 20) TimeStamp (smalldatetime)
------- ------------- ---------------
73 Start <T1>
73 Misc <T2>
73 End <T3>
81 Start <T1'>
81 Misc <T2'>
81 End <T3'>
....

I need to calculate End - Start for each unique ID (i.e. T3-T1 and
T3'-T1') and then take the average of those (2 in this case) entries.

Any help is appreciated.

Alex.
Jul 20 '05 #1
8 1681
hf*****@yahoo.com (Alex) wrote in message news:<c5**************************@posting.google. com>...
My table is laid out as such:

ID (int) What (varchar 20) TimeStamp (smalldatetime)
------- ------------- ---------------
73 Start <T1>
73 Misc <T2>
73 End <T3>
81 Start <T1'>
81 Misc <T2'>
81 End <T3'>
...

I need to calculate End - Start for each unique ID (i.e. T3-T1 and
T3'-T1') and then take the average of those (2 in this case) entries.

Any help is appreciated.

Alex.


Ps: I am running SQL 2000 SP3 and am looking for the stored procedure
code that'll accomplish the above.
Jul 20 '05 #2
Try something like:

CREATE TABLE MyTable
(
ID int NOT NULL,
What varchar(5) NOT NULL,
MyTimeStamp smalldatetime NOT NULL,
CONSTRAINT PK_MyTable PRIMARY KEY (ID, What)
)
GO

INSERT INTO MyTable VALUES(73, 'Start', '20040901')
INSERT INTO MyTable VALUES(73, 'Misc', '20040905')
INSERT INTO MyTable VALUES(73, 'End', '20040909')
INSERT INTO MyTable VALUES(81, 'Start', '20040915')
INSERT INTO MyTable VALUES(81, 'Misc', '20040917')
INSERT INTO MyTable VALUES(81, 'End', '20040919')
GO

CREATE PROCEDURE GetAverageMinutes
AS
SELECT
AVG(DATEDIFF(mi, a.MyTimeStamp, b.MyTimeStamp)) AS AverageMinutes
FROM MyTable a
JOIN MyTable b ON
b.ID = a.ID AND
a.What = 'Start' AND
b.What = 'End'
GO

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Alex" <hf*****@yahoo.com> wrote in message
news:c5**************************@posting.google.c om...
hf*****@yahoo.com (Alex) wrote in message
news:<c5**************************@posting.google. com>...
My table is laid out as such:

ID (int) What (varchar 20) TimeStamp (smalldatetime)
------- ------------- ---------------
73 Start <T1>
73 Misc <T2>
73 End <T3>
81 Start <T1'>
81 Misc <T2'>
81 End <T3'>
...

I need to calculate End - Start for each unique ID (i.e. T3-T1 and
T3'-T1') and then take the average of those (2 in this case) entries.

Any help is appreciated.

Alex.


Ps: I am running SQL 2000 SP3 and am looking for the stored procedure
code that'll accomplish the above.

Jul 20 '05 #3
Your design is fundamentally wrong. The flaw is called "attribute
splitting" and you can Google it. Time comes in durations and not
points (see Einstein and Zeno for the details). The DDL that you did
not post should have looked more like this:

CREATE TABLE Foobar
(event_id INTEGRR NOT NULL PRIMARY KEY,
event-description VARCHAR(20) NOT NULL,
start_time TIMESTAMP NOT NULL,
end_time TIMESTAMP NOT NULL,
CHECK (start_time < end_time));
I need to calculate End - Start for each unique ID (i.e. T3-T1 and

T3'-T1') and then take the average of those (2 in this case) entries. <<

Since you used Standard SQL TIMESTAMP in your pseudo-code, here is the
trivial answer:

SELECT AVG(INTERVAL (end_time - start_time) SECONDS)
FROM Foobar;

A proper design saves orders of magnitude in the queries.

Your problem is that: (1) you do not understand time; no great shame
there, since most people get it messed up (2) You designed a table to
mimick a paper form, namely the list you used for keeping track of
things. Think more abstractly; one attribute can be split in many
fields on the non-relational side, but must bre put into one and only
one column when it gets to the database.

The other answers you get will be fancy self-joins that bring the
durations make from the attribute split.

--CELKO--
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #4
Dan, that's beautiful. Thanks. I have a follow up question:

If the "End" time stamp were not unique, meaning that the "End" time
stamp could occur multiple times and I had to take the last one for
the purposes of the average computation what would the SQL look like
then?

Thanks again.

Alex.

"Dan Guzman" <gu******@nospam-online.sbcglobal.net> wrote in message news:<Ze***************@newssvr30.news.prodigy.com >...
Try something like:

CREATE TABLE MyTable
(
ID int NOT NULL,
What varchar(5) NOT NULL,
MyTimeStamp smalldatetime NOT NULL,
CONSTRAINT PK_MyTable PRIMARY KEY (ID, What)
)
GO

INSERT INTO MyTable VALUES(73, 'Start', '20040901')
INSERT INTO MyTable VALUES(73, 'Misc', '20040905')
INSERT INTO MyTable VALUES(73, 'End', '20040909')
INSERT INTO MyTable VALUES(81, 'Start', '20040915')
INSERT INTO MyTable VALUES(81, 'Misc', '20040917')
INSERT INTO MyTable VALUES(81, 'End', '20040919')
GO

CREATE PROCEDURE GetAverageMinutes
AS
SELECT
AVG(DATEDIFF(mi, a.MyTimeStamp, b.MyTimeStamp)) AS AverageMinutes
FROM MyTable a
JOIN MyTable b ON
b.ID = a.ID AND
a.What = 'Start' AND
b.What = 'End'
GO

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Alex" <hf*****@yahoo.com> wrote in message
news:c5**************************@posting.google.c om...
hf*****@yahoo.com (Alex) wrote in message
news:<c5**************************@posting.google. com>...
My table is laid out as such:

ID (int) What (varchar 20) TimeStamp (smalldatetime)
------- ------------- ---------------
73 Start <T1>
73 Misc <T2>
73 End <T3>
81 Start <T1'>
81 Misc <T2'>
81 End <T3'>
...

I need to calculate End - Start for each unique ID (i.e. T3-T1 and
T3'-T1') and then take the average of those (2 in this case) entries.

Any help is appreciated.

Alex.


Ps: I am running SQL 2000 SP3 and am looking for the stored procedure
code that'll accomplish the above.

Jul 20 '05 #5
Try this:

SELECT AVG(Duration)
FROM (
SELECT DATEDIFF(minute,MIN(MyTimeStap),MAX(MyTimeStamp)) AS Duration
FROM MyTable
GROUP BY ID
) AS T1

By the way: this is not a homework assignment, is it?

Gert-Jan

Alex wrote:

Dan, that's beautiful. Thanks. I have a follow up question:

If the "End" time stamp were not unique, meaning that the "End" time
stamp could occur multiple times and I had to take the last one for
the purposes of the average computation what would the SQL look like
then?

Thanks again.

Alex.

"Dan Guzman" <gu******@nospam-online.sbcglobal.net> wrote in message news:<Ze***************@newssvr30.news.prodigy.com >...
Try something like:

CREATE TABLE MyTable
(
ID int NOT NULL,
What varchar(5) NOT NULL,
MyTimeStamp smalldatetime NOT NULL,
CONSTRAINT PK_MyTable PRIMARY KEY (ID, What)
)
GO

INSERT INTO MyTable VALUES(73, 'Start', '20040901')
INSERT INTO MyTable VALUES(73, 'Misc', '20040905')
INSERT INTO MyTable VALUES(73, 'End', '20040909')
INSERT INTO MyTable VALUES(81, 'Start', '20040915')
INSERT INTO MyTable VALUES(81, 'Misc', '20040917')
INSERT INTO MyTable VALUES(81, 'End', '20040919')
GO

CREATE PROCEDURE GetAverageMinutes
AS
SELECT
AVG(DATEDIFF(mi, a.MyTimeStamp, b.MyTimeStamp)) AS AverageMinutes
FROM MyTable a
JOIN MyTable b ON
b.ID = a.ID AND
a.What = 'Start' AND
b.What = 'End'
GO

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Alex" <hf*****@yahoo.com> wrote in message
news:c5**************************@posting.google.c om...
hf*****@yahoo.com (Alex) wrote in message
news:<c5**************************@posting.google. com>...
> My table is laid out as such:
>
> ID (int) What (varchar 20) TimeStamp (smalldatetime)
> ------- ------------- ---------------
> 73 Start <T1>
> 73 Misc <T2>
> 73 End <T3>
> 81 Start <T1'>
> 81 Misc <T2'>
> 81 End <T3'>
> ...
>
> I need to calculate End - Start for each unique ID (i.e. T3-T1 and
> T3'-T1') and then take the average of those (2 in this case) entries.
>
> Any help is appreciated.
>
> Alex.

Ps: I am running SQL 2000 SP3 and am looking for the stored procedure
code that'll accomplish the above.


--
(Please reply only to the newsgroup)
Jul 20 '05 #6
Got it going. Thanks. The insight was really the self-join that Dan
mentioned. It was a minor tweak to get the rest working. Thanks for
all your help. And no it's not a homework assignment. :)

Gert-Jan Strik <so***@toomuchspamalready.nl> wrote in message news:<41***************@toomuchspamalready.nl>...
Try this:

SELECT AVG(Duration)
FROM (
SELECT DATEDIFF(minute,MIN(MyTimeStap),MAX(MyTimeStamp)) AS Duration
FROM MyTable
GROUP BY ID
) AS T1

By the way: this is not a homework assignment, is it?

Gert-Jan

Alex wrote:

Dan, that's beautiful. Thanks. I have a follow up question:

If the "End" time stamp were not unique, meaning that the "End" time
stamp could occur multiple times and I had to take the last one for
the purposes of the average computation what would the SQL look like
then?

Thanks again.

Alex.

"Dan Guzman" <gu******@nospam-online.sbcglobal.net> wrote in message news:<Ze***************@newssvr30.news.prodigy.com >...
Try something like:

CREATE TABLE MyTable
(
ID int NOT NULL,
What varchar(5) NOT NULL,
MyTimeStamp smalldatetime NOT NULL,
CONSTRAINT PK_MyTable PRIMARY KEY (ID, What)
)
GO

INSERT INTO MyTable VALUES(73, 'Start', '20040901')
INSERT INTO MyTable VALUES(73, 'Misc', '20040905')
INSERT INTO MyTable VALUES(73, 'End', '20040909')
INSERT INTO MyTable VALUES(81, 'Start', '20040915')
INSERT INTO MyTable VALUES(81, 'Misc', '20040917')
INSERT INTO MyTable VALUES(81, 'End', '20040919')
GO

CREATE PROCEDURE GetAverageMinutes
AS
SELECT
AVG(DATEDIFF(mi, a.MyTimeStamp, b.MyTimeStamp)) AS AverageMinutes
FROM MyTable a
JOIN MyTable b ON
b.ID = a.ID AND
a.What = 'Start' AND
b.What = 'End'
GO

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Alex" <hf*****@yahoo.com> wrote in message
news:c5**************************@posting.google.c om...
> hf*****@yahoo.com (Alex) wrote in message
> news:<c5**************************@posting.google. com>...
>> My table is laid out as such:
>>
>> ID (int) What (varchar 20) TimeStamp (smalldatetime)
>> ------- ------------- ---------------
>> 73 Start <T1>
>> 73 Misc <T2>
>> 73 End <T3>
>> 81 Start <T1'>
>> 81 Misc <T2'>
>> 81 End <T3'>
>> ...
>>
>> I need to calculate End - Start for each unique ID (i.e. T3-T1 and
>> T3'-T1') and then take the average of those (2 in this case) entries.
>>
>> Any help is appreciated.
>>
>> Alex.
>
> Ps: I am running SQL 2000 SP3 and am looking for the stored procedure
> code that'll accomplish the above.

Jul 20 '05 #7
Joe, although you seem to have a good grasp of time and its nuances, I
am not sure if you tried to solve my problem or found it easier (i.e.
less time) to solve your own. But thanks for the brief time you
alloted to my post and replying. A.

Ps: you were right about the DDL. I should have posted one. Sorry
and will do better next time.

Joe Celko <jc*******@earthlink.net> wrote in message news:<41**********************@news.newsgroups.ws> ...
Your design is fundamentally wrong. The flaw is called "attribute
splitting" and you can Google it. Time comes in durations and not
points (see Einstein and Zeno for the details). The DDL that you did
not post should have looked more like this:

CREATE TABLE Foobar
(event_id INTEGRR NOT NULL PRIMARY KEY,
event-description VARCHAR(20) NOT NULL,
start_time TIMESTAMP NOT NULL,
end_time TIMESTAMP NOT NULL,
CHECK (start_time < end_time));
I need to calculate End - Start for each unique ID (i.e. T3-T1 and

T3'-T1') and then take the average of those (2 in this case) entries. <<

Since you used Standard SQL TIMESTAMP in your pseudo-code, here is the
trivial answer:

SELECT AVG(INTERVAL (end_time - start_time) SECONDS)
FROM Foobar;

A proper design saves orders of magnitude in the queries.

Your problem is that: (1) you do not understand time; no great shame
there, since most people get it messed up (2) You designed a table to
mimick a paper form, namely the list you used for keeping track of
things. Think more abstractly; one attribute can be split in many
fields on the non-relational side, but must bre put into one and only
one column when it gets to the database.

The other answers you get will be fancy self-joins that bring the
durations make from the attribute split.

--CELKO--
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Jul 20 '05 #8
>> Joe, although you seem to have a good grasp of time and its nuances,
<<

Lord, no! That guy is Rick Snodgrass. his book on temproal queries in
SQL is on-line at his website at the University of AZ. I can simply
recognize the most common basic problems in DDL by sight now; I make a
part of my living fixing databases that look like what you posted.
I am not sure if you tried to solve my problem or found it easier (i.e.less time) to solve your own. <<

I published this kind of solution in SQL FOR SMARTIES, SQL PUZZLES and
several magazine columns years ago when I was still thinking of time as
points and not durations. How else would I know that there would have
to be an elaborate and error-prone self-join in whatever kludge got
posted? :)

Your problem *is* the design and that is the root of the difficulty in
even this simple query. It will get orders of magntiude worse. The
elaborate self-joins eat up time exponentially with DB size. A single
missing row throws reports off. Gaps are hard to detect.

I know; I have been paid to fix it before at a research company working
with a bank to look for patterns in checking account and credit card
balances. Hiring me for a month is expensive :)
Ps: you were right about the DDL. I should have posted one. Sorry and

will do better next time. <<

Nada. The number of frequent posters who have been asked over and over
and still will not post DDL is remarkable. Then of course there are the
guys who push a button and dump code in a format that only a machine
could love ..

--CELKO--
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: J | last post by:
Kind of new at programming/vb.net. I'm doing this junky die roller program. Heres's what is supposed to happen: Roll 2 6-sided dies. Add rolls together put total in rolls(d6total). Display...
2
by: johnywalkyra | last post by:
Hello, first of all sorry for crossposting, but I could not decide which group is more appropriate. To my question: Recently I've came across the code in GCC standard library, which computes the...
3
by: C++Geek | last post by:
I need to get this program to average the salaries. What am I doing wrong? //Program to read in employee data and calculate the average salaries of the emplyees.
4
by: sbowman | last post by:
I have a table with help desk ticketing information. There is a Date/Time open, Date/Time closed field both formatted as: MM/DD/YYYY hh:nn:ss I need to calculate the difference between these two...
3
by: mochatrpl | last post by:
I am looking for a way to make a query / report display the running average for total dollars. I have already set up a query to provide totals dollars per day from which a report graphly shows...
4
by: gaga | last post by:
hi guys, a part of my program requires me to calculate an average of items that are sold. the easiest way to do that would be writing a function, but im having trouble making up the parameters. if...
3
by: Salad | last post by:
http://www.mathwords.com/w/weighted_average.htm At the above link gives an example of a weighted average. It uses the following example: Grades are often computed using a weighted average....
10
by: vincex200 | last post by:
My group needs help with this program. We attempted to start it and got no where. Please help us. Write a C++ program that will read data from a file, perform computation on the data, then print...
14
by: Luna Moon | last post by:
Dear all, Can C++/STL/Boost do the vectorized calculation as those in Matlab? For example, in the following code, what I really want to do is to send in a vector of u's. All other...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.