Dear JS:
R, R1, and R2 are aliases. I would not say they are "alias tables" but
rather that they are independent instances of the same table. In other
words, "look at the same table without reference to any of the other
instances of that same table."
I did not provide a "difference between the last two meter redings" for each
meter. I provided the dates and meter readings. You certainly could
calculate the difference using what I gave.
Now, the concept of "the difference for all the readings" makes no sense to
me. Difference is "subtraction" and "subtraction" is a binary operation. A
difference is found between any two numbers, not a large set of numbers.
Please explain and give an example of what this means.
Reading the rest of what you say, I'm wondering if you want a "rolling
difference" between every consecutive pair of readings. Is this it?
There are no "loops" in SQL queries. But, if I understand you correctly,
the rolling difference could be done. I would simply exclude the first
reading from the list of readings, as there is no previous reading to that.
Did what I posted work well?
SELECT MeterNum, ReadDate, Read,
(SELECT MAX(ReadDate)
FROM tblReadings R1
WHERE R1.MeterNum = R.MeterNum
AND R1.ReadDate < R.ReadDate)
AS PrevDate,
(SELECT Read
FROM tblReadings R1
WHERE R1.MeterNum = R.MeterNum
AND R1.ReadDate =
(SELECT MAX(ReadDate)
FROM tblReadings R2
WHERE R2.MeterNum = R1.MeterNum
AND R2.ReadDate < R.ReadDate))
AS PrevRead
FROM tbl_Readings R
WHERE ReadDate > (
SELECT MIN(ReadDate)
FROM tblReadings R1
WHERE R1.MeterNum = R.MeterNum)
ORDER BY MeterNum, ReadDate
All I have done is to change the filter in the main part of the query so it
includes all the rows except the oldest.
I did not mention it before, but this presumes you never have two readings
for the same meter with the same ReadDate. That would create an ambiguous
situation and will probably cause an error when running the query, as it
would cause a subquery to return two values where only one is permitted.
For this reason, a constraint on your data to prevent that may be a good
idea, if it is not already in place. Whether this is appropriate may depend
on the overall design of the data, and is potentially a complex question
dealing with the original data design.
Tom Ellison