I have a database which, simiplified, is as follows :
ID | SecondID | DateRecorded | NumberToCheck | NumberToUpdate
NumberToUpdate currently has a value for 0 for all rows.
I wish to update NumberToUpdate with the value for NumberToCheck on the same row, MINUS the value for NumberToCheck which has the earliest DateRecorded “(Min(DateRecorded)” where NumberToCheck is greater than 0, and which has the same ID and secondID as the original row.
So far I have
UPDATE dbo.Table
SET NumberToUpdate =//Update NumberToUpdate
NumberToCheck - //NumberToCheck from the current row, subtracting...
(SELECT TOP 1 t2.NumberToCheck FROM Table t2 WHERE ID = t2.ID AND secondID = t2.secondID AND t2.DateRecorded =
(SELECT TOP 1 MIN(t3.DateRecorded) FROM Table t3 WHERE t2.ID = t3.ID AND t2.secondID = t3.secondID AND t3.Passes > 0))
//the NumberToCheck with the earliest date, of the same ID.
This is not correct however, and is returning me values which make no sense (including minus values of which there shouldn’t be any!)
What have I forgotten here?
Thanks very much
First, you should start with a select query to get the value you want:
Now, you can use this in your original update: