View Single Post

   
  #5 (permalink)  
Old 02-29-2008, 04:26 AM
Alex
 
Posts: n/a
Default Re: Average Computation Question

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" <guzmanda@nospam-online.sbcglobal.net> wrote in message news:<ZeA7d.660$Al3.412@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" <hfamili@yahoo.com> wrote in message
> news:c55acd4f.0410012006.456a44d7@posting.google.c om...
> > hfamili@yahoo.com (Alex) wrote in message
> > news:<c55acd4f.0410011405.39a448aa@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.

Reply With Quote