Showing posts with label average. Show all posts
Showing posts with label average. Show all posts

Wednesday, March 21, 2012

Query for 4 weeks average ..Need help

i have 3 tables, each with a date(it has daily dates) column(column name is same in all tables)
Each table has columns say "value1","value2", "value3"

i want data from all these tables together.such that my first column will have data weeks and other 3 columns count1,count2,count3 will have average of next 4 weeks count..placed infront of week.

weeks count(value1) count(value2) count(value3 )
1/1/2005 101 88 221
1/8/2005 100 81 151
1/15/2005 87 96 301

Average calculations Here :
week 1 2 3 4
Count1: 101 = ( 99 + 105 + 110 + 87 )/4
100 = (105 + 110 + 87 + 98 )/4


Plz lemme know if u have any suggestions..

Do you really mean "SUM" where you say "COUNT"?|||Also, are you wanting your weeks to run Sunday to Saturday?|||

Sumit:

I put this together. It parameterized to allow for variation of (1) a "from date", (2) a "to date", and (3) the "beginning day of the week" [here I am assuming Sunday]. This routine uses a "small_iterator" table to flash through and summarize the records that occur during the date range. I am assuming that what you want are 28-day averages from the date named through the 28 days that follow. My "small_iterator" table consists of the integers 1-32768 and is intended as a utility table that we generally make avaible to all application databases. Our standards for this table stress the use of the NOLOCK optimizer hint for this table to avoid lock contention. This simple table is defined as:


create table dbo.SMALL_ITERATOR
( iter smallint not null
constraint PK_SMALL_ITERATOR primary key
)

I hope the following is of use; I am not sure of all the requirements you have:

-- -
-- First, create a fake table with some fake data
-- -

set nocount on
create table ##xample
( xDate datetime not null,
value1 integer not null,
value2 integer not null,
value3 integer not null,

constraint pk_##xample primary key (xDate)
)

declare @.rootDate datetime
set @.rootDate = '11/19/2005' -- selecting a non-distinct date

declare @.iter integer
set @.iter = 0

while @.iter <= 250
begin

insert into ##xample
select dateadd (day, @.iter, @.rootDate),
1 + 60 * rand (),
1 + 40 * rand () + 40 * rand(),
1 + 50 * rand() + 50 * rand() + 50 * rand ()

set @.iter = @.iter + 1

end

--select * from ##xample -- To show the fake data if you want to see it

-- -
-- Establish some parameters to this report summary
--
-- In this example, we are going to assume that a week begins on Sunday
--
-- We are going to run this report from 1/1/2006 to the present; note
-- that since this uses an iterator table that the start date is set
-- to 12/31/2005 because dates are derived by using the iterator to
-- increment through the dates and the lowest iteration value is 1.
--
-- The @.baseWeekDate var is used to store the date on which the first
-- full week of the year begins minus one week (because of iterator table)
--
-- I am not sure about how the ranges are to run so maybe this helps,
-- maybe it doesn't
--
-- Notice that the "4-week" average rapidly shrinks for the data
-- at the end of the table; this is because we are taking a "4 week"
-- average with less than 28 days of data; you might want this handled
-- differently
-- -

declare @.fromDate datetime
declare @.toDate datetime
declare @.firstWeekDay integer
declare @.baseWeekDate datetime
declare @.maxIterator integer

set @.firstWeekDay = 1 -- Assume that Sunday is the beginning of the week
set @.fromDate = '12/31/5' -- The beginning of the year minus 1 day
set @.toDate = ( select max (xDate) from ##xample ) -- The highest date in the table
set @.maxIterator = 1 + datediff (day, @.fromDate, @.toDate) / 7 -- upper bound for iterator

-- -
-- Stuff is beginning to get more tricky here. I am looking for the
-- first Sunday the occurs at or after the "from date"; however, because
-- I am going to be using an iterator to bang throug the data, I must
-- back the that first Sunday date by a week.
-- -
select @.baseWeekDate = dateadd (day, -7 ,dateadd (day, iter, @.fromDate))
from small_iterator (nolock)
where iter <= 7
and datepart (dw, dateadd (day, iter, @.fromDate)) = @.firstWeekDay

-- Just used when I was debugging
/*
select @.fromDate as [@.fromDate],
@.toDate as [@.toDate],
@.firstWeekDay as [@.firstWeekDay],
@.baseWeekDate as [@.firstWeekDate],
@.maxIterator as [@.maxIterator]
*/

-- -
-- Heavy into it here:
--
-- This routine uses an iterator table to flash through all of the
-- starting week dates that occur between the from date and the to date
--
-- Compute the 4-week average for the data that begins with the listed
-- date and runs for the next 28 days
-- -
select convert (varchar (12), weekDate, 101) as [Week Date],
avgVal_1 as [Avg Val 1],
avgVal_2 as [Avg Val 2],
avgVal_3 as [Avg Val 3]
from ( select dateadd (day, 7*iter, @.baseWeekDate) as weekDate,
sum (value1) / 4 as avgVal_1,
sum (value2) / 4 as avgVal_2,
sum (value3) / 4 as avgVal_3
from small_iterator (nolock) -- don't want contention on an iterator
inner join ##xample
on xDate >= dateadd (day, 7*iter, @.baseWeekDate) -- bangs through all the sundays
and xDate < dateadd (day, 7*iter + 28, @.baseWeekDate) -- sets up a 4-week interval
where iter <= @.maxIterator
group by dateadd (day, 7*iter, @.baseWeekDate) -- Group the data by the week
) xx
order by weekDate

-- -
-- All done; let's drop the table and go home
-- -

go

drop table ##xample

|||Could you please post a sample schema, data and expected results?|||

I am so so thankful of u. i really wanted somthing of this type.

Now only problem is tat if the End Ref Date doesnt fall in the 4th week then the query will still give the average of 4 weeks, which is actually wrong.

i guess it should be like this

Last week --> no average

1 week b4 last week-->average of 2

2 weeks b4 last week --> avg of last 3 weeks

for other its as usual.

if u could reply me .it ll be really gr8..

Thanks & regards

Sumit

|||

Sumit:

In the comments I had:

--
-- Notice that the "4-week" average rapidly shrinks for the data
-- at the end of the table; this is because we are taking a "4 week"
-- average with less than 28 days of data; you might want this handled
-- differently

Is what you are seeking a solution to this problem that occurs over the last 28 days?

Dave

|||

Sorry for late reply..din see the Alert.

Actually ya u r rite..i was looking for average for last 28 days.

I had to make some reports on SQL Server2K Reporting Services.

The code which you sent, which included DDL n DML statements worked fine individually in Business Intelligence Studio but the dataset couldnt generate any particular fields. So i had to remove lot of things from the query, once i understood the login.it finally worked. Chart is coming fine.Thank u.

i have another question:

I have 3 fields say :

JOb Inactive Returned

ID1 2 3

ID2 5 1

ID3 2 6

ID4 1 5

ID5 5 4

ID6 2 6

ID7 1 5

i want data in such a way tat

Days_Count jobs_inactive Jobs_Returned

1 2 1

2 3 0

3 0 1

4 0 1

5 2 8 ( for 5 and Above days)

sql

Monday, March 12, 2012

query engine statitistics

Hi, Is there an esay way to gather information about how many times each
stored procedures has been called , the average execution time , etc ..
I know profiling can give you punctual info about this .. however i need
aggregated info over a determined period of time
thank in advance
best regards
Enrico Sabbadin
MTS/COM+/VBCOM/.NET FAQ: http://www.sabbasoft.com
BLOG: http://www.sabbasoft.com/myblog
Check out sys.dm_exec_query_stats if you are on 2005.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
<x> wrote in message news:OvENi8jcHHA.4820@.TK2MSFTNGP06.phx.gbl...
> Hi, Is there an esay way to gather information about how many times each stored procedures has
> been called , the average execution time , etc ..
> I know profiling can give you punctual info about this .. however i need aggregated info over a
> determined period of time
> thank in advance
> best regards
> --
> Enrico Sabbadin
> MTS/COM+/VBCOM/.NET FAQ: http://www.sabbasoft.com
> BLOG: http://www.sabbasoft.com/myblog
>

query engine statitistics

Hi, Is there an esay way to gather information about how many times each
stored procedures has been called , the average execution time , etc ..
I know profiling can give you punctual info about this .. however i need
aggregated info over a determined period of time
thank in advance
best regards
Enrico Sabbadin
MTS/COM+/VBCOM/.NET FAQ: http://www.sabbasoft.com
BLOG: http://www.sabbasoft.com/myblogCheck out sys.dm_exec_query_stats if you are on 2005.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
<x> wrote in message news:OvENi8jcHHA.4820@.TK2MSFTNGP06.phx.gbl...
> Hi, Is there an esay way to gather information about how many times each s
tored procedures has
> been called , the average execution time , etc ..
> I know profiling can give you punctual info about this .. however i need a
ggregated info over a
> determined period of time
> thank in advance
> best regards
> --
> Enrico Sabbadin
> MTS/COM+/VBCOM/.NET FAQ: http://www.sabbasoft.com
> BLOG: http://www.sabbasoft.com/myblog
>

query engine statitistics

Hi, Is there an esay way to gather information about how many times each
stored procedures has been called , the average execution time , etc ..
I know profiling can give you punctual info about this .. however i need
aggregated info over a determined period of time
thank in advance
best regards
--
Enrico Sabbadin
MTS/COM+/VBCOM/.NET FAQ: http://www.sabbasoft.com
BLOG: http://www.sabbasoft.com/myblogCheck out sys.dm_exec_query_stats if you are on 2005.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
<x> wrote in message news:OvENi8jcHHA.4820@.TK2MSFTNGP06.phx.gbl...
> Hi, Is there an esay way to gather information about how many times each stored procedures has
> been called , the average execution time , etc ..
> I know profiling can give you punctual info about this .. however i need aggregated info over a
> determined period of time
> thank in advance
> best regards
> --
> Enrico Sabbadin
> MTS/COM+/VBCOM/.NET FAQ: http://www.sabbasoft.com
> BLOG: http://www.sabbasoft.com/myblog
>

Saturday, February 25, 2012

Query Average Help

Hello I have the following table and data. I need to find the avg game attendance for homegame (where shcool = 'Indiana Univ.' and away games ( where opponent = 'Indiana Univ." This would be 3 columns listing the SCHOOL 'Indiana Univ.", AVG HOMEGAME ATTENDANCE, AVG AWAY ATTENDANCE. I have no clue how to format the query to get the last column.

- Thanks for your help and sugestions.

CREATE TABLE HOMEGAME
(school VARCHAR2(30),
hdate DATE,
opponent VARCHAR2(30),
attendance NUMBER(6),
self_score NUMBER(3),
opp_score NUMBER(3),
self_injuries NUMBER(3),
opp_injuries NUMBER(3));

INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 46000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 45000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 44000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 43000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 42000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 41000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 40000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 39000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 38000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 37000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Indiana Univ.', null, null, 36000, 0, 7, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 51000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 50000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 49000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 48000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 47000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 46000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 45000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 44000, 7, 0, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 43000, 0, 7, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 42000, 0, 7, null, null);
INSERT INTO homegame VALUES
('Penn State Univ.', null, 'Indiana Univ.', 41000, 0, 7, null, null);select 1,avg(goals) from table where it is home
union
select 2,avg(goals) from table where it is not home|||UNION is nice, but it returns 2 rows

Try

SELECT 'Indiana Univ.' as school,
avg(case school when 'Indiana Univ.' then attendance else null end) AS avg_homegame,
avg(case opponent when 'Indiana Univ.' then attendance else null end) AS avg_awaygame
from homegame;

It returns :

SCHOOL AVG_HOMEGAME AVG_AWAYGAME
Indiana Univ. 41000 46000|||- Thanks for the Reply. Never used case before. I have tried moving the parethesis aronund bet keep getting the belower error?

SQL> SELECT 'Indiana Univ.' as school,
2 avg(case school when 'Indiana Univ.' then attendance else null end) AS avg_homegame,
3 avg(case opponent when 'Indiana Univ.' then attendance else null end) AS avg_awaygame
4 from homegame;
avg(case school when 'Indiana Univ.' then attendance else null end) AS avg_homegame,
*
ERROR at line 2:
ORA-00907: missing right parenthesis

SQL>|||I guess you are using an Oracle version that doesn't support CASE (e.g. 8.1.6)

Instead, you can use the good old DECODE.

This does not work :
SQL> SELECT (CASE 1 WHEN 1 THEN 'TRUE' ELSE 'FALSE' END) FROM DUAL;
SELECT (CASE 1 WHEN 1 THEN 'TRUE' ELSE 'FALSE' END) FROM DUAL
*
ERROR at line 1:
ORA-00907: missing right parenthesis

But this might work :
SQL> SELECT DECODE(1,1,'TRUE','FALSE') FROM DUAL;

DECO
--
TRUE

So, in your case :
SELECT 'Indiana Univ.' as school,
avg(decode(school,'Indiana Univ.',attendance,null)) AS avg_homegame,
avg(decode(opponent,'Indiana Univ.',attendance,null)) AS avg_awaygame
FROM homegame;

Monday, February 20, 2012

Query Assistance - Average Days Between Services

Hi,
I need some help writing a two queries to determine the average number of
days between services for 1. a specific machineid 2. for all specific
machineids.
The table contains many columns including a MachineID column (INT) and a
ServiceDate column (DATETIME) so sample data (excluding other columns) would
look like:
MachineID ServiceDate
123 2005-01-14 00:00:00
123 2005-02-10 00:00:00
123 2005-03-14 00:00:00
124 2005-02-18 00:00:00
123 2005-05-14 00:00:00
124 2005-03-14 00:00:00
124 2005-05-14 00:00:00
The is no IDENTITY column on the table.
So the resultsets would resemble:
1. For a specific machineid
MachineID Average Days Between Services
123 40
2. For all machineids
MachineID Average Days Between Services
123 40
124 42.5
It seems simple but I'm struggling with this one!
Please let me know if you need additional information.
Thanks
JerryJerry,
I think this will do what you want. If you want all MachineID values
listed, even if there is only one ServiceDate, it would help to have a
table of MachineID values, which you can LEFT JOIN so you get
them to appear with NULL average if they appear fewer than twice
in the service table.
If you want the dates to be interpreted correctly in all locales, add
the T between the date and time. The format you are using is not
independent of language and dateformat setting.
Steve Kass
Drew University
set nocount on
go
create table T (
MachineID int,
ServiceDate datetime
)
insert into T values (123,'2005-01-14T00:00:00')
insert into T values (123,'2005-02-10T00:00:00')
insert into T values (123,'2005-03-14T00:00:00')
insert into T values (124,'2005-02-18T00:00:00')
insert into T values (123,'2005-05-14T00:00:00')
insert into T values (124,'2005-03-14T00:00:00')
insert into T values (124,'2005-05-14T00:00:00')
go
select
MachineID, avg(Gap) as AvgGap
from (
select
T1.MachineID,
1.0*datediff(day,T1.ServiceDate,min(T2.ServiceDate)) as Gap
from T as T1
join T as T2
on T2.MachineID = T1.MachineID
where T2.MachineID = T1.MachineID
and T2.ServiceDate > T1.ServiceDate
group by T1.MachineID, T1.ServiceDate
) T
group by MachineID
go
drop table T
Jerry Spivey wrote:

>Hi,
>I need some help writing a two queries to determine the average number of
>days between services for 1. a specific machineid 2. for all specific
>machineids.
>The table contains many columns including a MachineID column (INT) and a
>ServiceDate column (DATETIME) so sample data (excluding other columns) woul
d
>look like:
>MachineID ServiceDate
>123 2005-01-14 00:00:00
>123 2005-02-10 00:00:00
>123 2005-03-14 00:00:00
>124 2005-02-18 00:00:00
>123 2005-05-14 00:00:00
>124 2005-03-14 00:00:00
>124 2005-05-14 00:00:00
>The is no IDENTITY column on the table.
>So the resultsets would resemble:
>1. For a specific machineid
>MachineID Average Days Between Services
>123 40
>2. For all machineids
>MachineID Average Days Between Services
>123 40
>124 42.5
>It seems simple but I'm struggling with this one!
>Please let me know if you need additional information.
>Thanks
>Jerry
>
>
>
>
>
>|||Try,
use northwind
go
create table t1 (
MachineID int not null,
ServiceDate datetime not null,
constraint pk_t1 primary key (MachineID, ServiceDate)
)
go
insert into t1 values(123, '2005-01-14 00:00:00')
insert into t1 values(123, '2005-02-10 00:00:00')
insert into t1 values(123, '2005-03-14 00:00:00')
insert into t1 values(124, '2005-02-18 00:00:00')
insert into t1 values(123, '2005-05-14 00:00:00')
insert into t1 values(124, '2005-03-14 00:00:00')
insert into t1 values(124, '2005-05-14 00:00:00')
go
create view v1
as
select
a.MachineID,
a.ServiceDate,
datediff(day, b.ServiceDate, a.ServiceDate) * 1.0 as days_since_last_serv
from
t1 as a
inner join
t1 as b
on a.MachineID = b.MachineID
and b.ServiceDate = (select max(c.ServiceDate) from t1 as c where
c.MachineID = a.MachineID and c.ServiceDate < a.ServiceDate)
where
datediff(day, b.ServiceDate, a.ServiceDate) is not null
go
select
*
from
v1
order by
MachineID,
ServiceDate
go
select
MachineID,
avg(days_since_last_serv) as [Average Days Between Services]
from
v1
group by
MachineID
order by
MachineID
go
select
MachineID,
avg(days_since_last_serv) as [Average Days Between Services]
from
v1
where
MachineID = 123
group by
MachineID
go
drop view v1
go
drop table t1
go
AMB
"Jerry Spivey" wrote:

> Hi,
> I need some help writing a two queries to determine the average number of
> days between services for 1. a specific machineid 2. for all specific
> machineids.
> The table contains many columns including a MachineID column (INT) and a
> ServiceDate column (DATETIME) so sample data (excluding other columns) wou
ld
> look like:
> MachineID ServiceDate
> 123 2005-01-14 00:00:00
> 123 2005-02-10 00:00:00
> 123 2005-03-14 00:00:00
> 124 2005-02-18 00:00:00
> 123 2005-05-14 00:00:00
> 124 2005-03-14 00:00:00
> 124 2005-05-14 00:00:00
> The is no IDENTITY column on the table.
> So the resultsets would resemble:
> 1. For a specific machineid
> MachineID Average Days Between Services
> 123 40
> 2. For all machineids
> MachineID Average Days Between Services
> 123 40
> 124 42.5
> It seems simple but I'm struggling with this one!
> Please let me know if you need additional information.
> Thanks
> Jerry
>
>
>
>
>
>|||SELECT
MachineID,
(datediff(d, min(ServiceDate), max(ServiceDate))/ (count(machineid)-1)) as
AverageDays FROM TABLE1
GROUP BY MachineId
ORDER BY Machineid
--
Programmer
"Jerry Spivey" wrote:

> Hi,
> I need some help writing a two queries to determine the average number of
> days between services for 1. a specific machineid 2. for all specific
> machineids.
> The table contains many columns including a MachineID column (INT) and a
> ServiceDate column (DATETIME) so sample data (excluding other columns) wou
ld
> look like:
> MachineID ServiceDate
> 123 2005-01-14 00:00:00
> 123 2005-02-10 00:00:00
> 123 2005-03-14 00:00:00
> 124 2005-02-18 00:00:00
> 123 2005-05-14 00:00:00
> 124 2005-03-14 00:00:00
> 124 2005-05-14 00:00:00
> The is no IDENTITY column on the table.
> So the resultsets would resemble:
> 1. For a specific machineid
> MachineID Average Days Between Services
> 123 40
> 2. For all machineids
> MachineID Average Days Between Services
> 123 40
> 124 42.5
> It seems simple but I'm struggling with this one!
> Please let me know if you need additional information.
> Thanks
> Jerry
>
>
>
>
>
>|||CREATE TABLE ServiceLog
(machine_id INTEGER NOT NULL,
service_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
CHECK (service_date
= CAST(CEILING (CAST(service_date AS FLOAT)) AS DATETIME)), --drop
time
PRIMARY KEY (machine_id, service_date));
INSERT INTO ServiceLog VALUES (123, '2005-01-14 00:00:00');
INSERT INTO ServiceLog VALUES (123, '2005-02-10 00:00:00');
INSERT INTO ServiceLog VALUES (123, '2005-03-14 00:00:00');
INSERT INTO ServiceLog VALUES (123, '2005-05-14 00:00:00');
INSERT INTO ServiceLog VALUES (124, '2005-02-18 00:00:00');
INSERT INTO ServiceLog VALUES (124, '2005-03-14 00:00:00');
INSERT INTO ServiceLog VALUES (124, '2005-05-14 00:00:00');
SELECT machine_id,
DATEDIFF(DD, MIN(service_date), MAX(service_date))
/ (1.0 *COUNT(*)) AS avg_gap
FROM ServiceLog
GROUP BY machine_id;
This gives me:
macine_id avg_gap
===============
123 30.00
124 28.33
Which look more correct than your 40 days just by eyeballing it -- i.e.
you service things around the 15-th of each month. I did this problem
years ago and got caught in the "procedural mindset" trap like Steve
did. This where you compute each INDIVIDUAL gap between events and
then use an average function on them. Instead think of each machine as
a grouping (subset) that has properties as a whole -- duration range,
and count of events.|||Ok you three are absolutely brilliant!!!
Now just trying to figure out the logic that you used :-) May have a few
questions for you in a few.
Thanks again!!!!
Jerry
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:O5sExXgYFHA.3840@.tk2msftngp13.phx.gbl...
> Hi,
> I need some help writing a two queries to determine the average number of
> days between services for 1. a specific machineid 2. for all specific
> machineids.
> The table contains many columns including a MachineID column (INT) and a
> ServiceDate column (DATETIME) so sample data (excluding other columns)
> would look like:
> MachineID ServiceDate
> 123 2005-01-14 00:00:00
> 123 2005-02-10 00:00:00
> 123 2005-03-14 00:00:00
> 124 2005-02-18 00:00:00
> 123 2005-05-14 00:00:00
> 124 2005-03-14 00:00:00
> 124 2005-05-14 00:00:00
> The is no IDENTITY column on the table.
> So the resultsets would resemble:
> 1. For a specific machineid
> MachineID Average Days Between Services
> 123 40
> 2. For all machineids
> MachineID Average Days Between Services
> 123 40
> 124 42.5
> It seems simple but I'm struggling with this one!
> Please let me know if you need additional information.
> Thanks
> Jerry
>
>
>
>
>|||God, I get sloppy! I forgot to remove one of the days at the end of the
total duration.
SELECT machine_id,
DATEDIFF(DD, MIN(service_date), MAX(service_date))
/ (1.0 *COUNT(*) -1) AS avg_gap
FROM ServiceLog
GROUP BY machine_id;|||Sergey,
If I add only record for a machine I get a divide by zero error. How can I
fix that just in case the data contains only one record for a machineid?
Thanks again.
Jerry
"Sergey Zuyev" <SergeyZuyev@.discussions.microsoft.com> wrote in message
news:6CE8FE0C-FCF0-4E3C-AAF6-F395485F32C4@.microsoft.com...
> SELECT
> MachineID,
> (datediff(d, min(ServiceDate), max(ServiceDate))/ (count(machineid)-1))
> as
> AverageDays FROM TABLE1
> GROUP BY MachineId
> ORDER BY Machineid
> --
> Programmer
>
> "Jerry Spivey" wrote:
>|||I think I got it - added a HAVING COUNT(*) > 1 to the query.
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:%23t5HC4gYFHA.2124@.TK2MSFTNGP14.phx.gbl...
> Sergey,
> If I add only record for a machine I get a divide by zero error. How can
> I fix that just in case the data contains only one record for a machineid?
> Thanks again.
> Jerry
> "Sergey Zuyev" <SergeyZuyev@.discussions.microsoft.com> wrote in message
> news:6CE8FE0C-FCF0-4E3C-AAF6-F395485F32C4@.microsoft.com...
>|||something like that, but im not sure that is the best approach
SELECT
MachineID,
(datediff(d, min(ServiceDate), max(ServiceDate))/ Case
(Count(MachineID)-1) WHEN 0 THEN 1 ELSE (Count(MachineID)-1) END) as
AverageDays FROM TABLE1
GROUP BY MachineId
ORDER BY Machineid
--
Programmer
"Jerry Spivey" wrote:

> Sergey,
> If I add only record for a machine I get a divide by zero error. How can
I
> fix that just in case the data contains only one record for a machineid?
> Thanks again.
> Jerry
> "Sergey Zuyev" <SergeyZuyev@.discussions.microsoft.com> wrote in message
> news:6CE8FE0C-FCF0-4E3C-AAF6-F395485F32C4@.microsoft.com...
>
>