select top 1 ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
Eventcode, eventtime as et, status from cfw.dbo.DCTBLEVENTINFO
where MeterID = 4722 and EventTime between convert(date,'2011-10-21')
and dateadd(day,1,convert(date,'2011-10-26'))
and EventCode = 13
Original resultset:
id Eventcode et status
1 13 2011-10-26 15:00:00.000 1
The above query returns the perfect result set, but if I use the same query like the following manner it returns the wrong result
SELECT temp.et
FROM (SELECT TOP 1 ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
Eventcode,
eventtime as et,
status
FROM cfw.dbo.DCTBLEVENTINFO
WHERE MeterID = 4722
AND EventTime BETWEEN CONVERT(date,'2011-10-21')
AND DATEADD(day,1,convert(date,'2011-10-26'))
AND EventCode = 13) temp
WHERE status = 1
Result set for the above query :
et
------------------------
2011-10-21 21:42:00.000
It returns some other date. I can’t find the problem.
Try adding an ORDER BY to your sub select.
Something like
Please always remember Without ORDER BY, there is no default sort order.
Furthermore, remeber the Logical Query Processing Phases – Order of Statement Execution