I have a table in which I keep different meters (water meter, electricity meter), and in another table I save the readings for each meter. The structure of the table is as follows: Table of counters
MeterID | MeterType | MeterName
Indication table:
ReadingID | MeterID | Index | DateOfReading
Readings for the meter are read monthly. What I'm trying to do now is get the Meter information, the current read and the previous read in just one line. Therefore, if I had a request, the following line:
MeterID | MeterType | MeterName | CurrnetIndex | LastIndex
I have the following query:
SELECT Meter.MeterID, Meter.MeterType, Meter.MeterName, CurrentReading.Index, PreviousReading.Index
FROM Meters AS Meter
LEFT OUTER JOIN Readings AS CurrentReading ON Meter.MeterID = CurrentReading.MeterID
LEFT OUTER JOIN Readings AS PreviousReading ON Meter.MeterID = PreviouseReading.MeterID
WHERE CurrentReading.ReadingID != PreviousReading.ReadingID AND DIMESTAMPDIFF(MONTH, CurrentReading.DateOfReading, PreviousReding.DateOfReading)=-1
The problem is that I may not have the current reading or the previous one, or both, but I still need to get information about the meter. It is perfectly acceptable for me to get NULL columns, but I still need a row :)