I have a data set that i am attempting to select the first record with a station id of 2.
InspectionNbr Station DateTimeStamp
825065 1 2010-11-16 04:38:49.000
825065 2 2010-11-16 12:38:31.000
825065 2 2010-12-06 01:35:14.000
825065 2 2011-01-24 08:11:04.000
In this case i want to select the second line of the results. How can i use SQL to get the minimum date where stationid = 2?
That being stated, this is what i have.
i created a temporary table in SQL. i have it setup to populate the table with the latest date. Then i attempt and update the temporary table with the following code
UPDATE @report_out
set
DateTimeStamp = Min(si.CreatedDate)
from
@report_out as r
INNER JOIN
StationInspection as si
on si.ModifiedDate = r.DateTimeStamp
where
r.Station = 2
For some reason beyond me it doesn’t like the DateTimeStamp = Min(si.CreatedDate)
i get the follwing error:
An aggregate may not appear in the set list of an UPDATE statement.
any pointers?
As far as I can figure out, an aggregate can’t be used in an update statement because the aggregate and the update affect two different row sets. Think about a normal SELECT with an aggregate:
The aggregate works on all rows in the row set. The row set is determined by the WHERE clause, which determines which rows will be in the row set.
In an update statement, the WHERE clause determines which rows will be changed:
The update affects all rows in the row set (all rows that pass the filter specified by the WHERE clause).
So, in the case where you try to do both (I realize this is somewhat simplified from your code, but it makes the point):
You have two operations that require unique row sets, but only one row set selector (WHERE clause).
SQL doesn’t support two WHERE clauses in a single statement. So you’ll need two statements: