-----Original Message-----
Hi,
If you have large tables, it may be preferable to use temporary tables,
temp1 and temp2, each one having an autonumber field, f1, and your key
field, pk.
Step1. Fill your temp tables.
INSERT INTO temp1(pk) SELECT pk FROM myTable ORDER BY [time] ASC;
INSERT INTO temp2(pk) SELECT pk FROM myTable ORDER BY onoff, [time]
ASC;
Step2. Create the result.
SELECT x.onoff, MAX(x.countOf)
FROM ( SELECT onoff, COUNT(*) as CountOf
FROM (myTable INNER JOIN temp1 ON temp1.pk=myTable.pk)
INNER JOIN temp2 ON temp2.pk=myTable.pk
GROUP BY onoff, temp1.f1-temp2.f1
) as x
GROUP BY x.onoff
Step3 Cleaning
DROP TABLE temp1
DROP TABLE temp2
So, what is going on? better working with an example for illustration.
With your date, temp1 is
f1 key
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
but if your key was not sequential, uninterruped, f1 would be.
temp2 is ordering the on (-1) first:
f1, key key time onoff
1 1 -> 1 10:09 on
2 2 -> 2 10:10 on
3 4 -> 4 10:12 on
4 8 -> 8 10:16 on
5 3 -> 3 10:11 off
6 5 -> 5 10:13 off
7 6 -> 6 10:14 off
8 7 -> 7 10:15 off
ie, the on first, the off after, and in case of equality, accordingly to the
key (or the time, in fact)
Now, the step 2 just subtrat the f1 values for the same key:
key temp1.f1 temp2.f1 difference
1 1 1 0
2 2 2 0
3 3 5 -2
4 4 3 1
5 5 6 -1
6 6 7 -1
7 7 8 -1
8 8 4 4
so, these difference used as group, now make the COUNT(*)
difference COUNT(*) associated_on/off
0 2 on
-2 1 off
1 1 on
-1 3 off
4 1 on
(we keept track of the associated on/off by grouping on those values, in
addition to the differences).
and finally, finding the max (count ) for each on/off
on 2
off 3
Hoping it may help,
Vanderghast, Access MVP
Thanks for the reply Tom.
The order of the data in the table is by time. There are 3
fields in the table status, key(auto number), time, onoff.
Data is in order of oldest to newest, so as far as order I
need to base the "consecutive" on's or off's it would be
by the key from smallest to largest. Example
Key Time OnOff
1 10:09 on
2 10:10 on
3 10:11 off
4 10:12 on
5 10:13 off
6 10:14 off
7 10:15 off
8 10:16 on
Thanks for the help, Mark
that
define that the
term order,
based on the MAX
() in a with
no
.