I have two tables.
TableA
Userid Starttime reason
John yyyy-mm-dd hh:mm:ss logged in
Table B
Userid Date Starttime reason
John yyyy-mm-dd yyyy-mm-dd hh:mm:ss logged in
I need to update the starttime of table B with min(a.starttime) while a.Userid = b.userid, a.starttime = b.date, and reason = ‘logged in’.
I seem to be having issues with using Min(a.starttime) as what I want to use to update.
My query is below:
update B
set B.starttime = (
select Min(A.Starttime)
from table as A
where B.UserID = A.UserID
and (CONVERT(DATETIME,A.DATE,102)) = (CONVERT(DATETIME,B.Date,102)))
and (A.Reason = 'loggedin')
)
from table2 as B
I convert the dates since table B has the date as for example 2011-09-13 00:00:00 and A has the date and times.
If you’re just not getting the right results, it may be because you need to use convert(varchar, date, 102) instead of convert(datetime, date, 102). If that doesn’t help, try this.
Instead of doing the subquery inside the SET portion, use it as a derived table and JOIN to it. Even if the above fixes the results, the below query should be far more efficient.