使用MIN更新

时间:2011-09-14 18:54:15

标签: sql sql-server-2005

我有两张桌子。

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

我需要用min(a.starttime)更新表B的开始时间,而a.Userid = b.userid,a.starttime = b.date,并且reason ='登录'。

我似乎遇到使用Min(a.starttime)作为我想用来更新的问题。

我的查询如下:

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

我转换日期,因为表B的日期为2011-09-13 00:00:00,A有日期和时间。

2 个答案:

答案 0 :(得分:5)

如果你没有得到正确的结果,可能是因为你需要使用convert(varchar,date,102)而不是convert(datetime,date,102)。如果这没有用,试试这个。

不要在SET部分中执行子查询,而是将其用作派生表并加入它。即使以上修复了结果,下面的查询应该更有效率。

update B
set B.starttime = A.starttime
from table2 as B
INNER JOIN (
select A.UserId, convert(varchar, A.Date, 102) as adate, Min(A.Starttime) as starttime
  from table as A
  WHERE  (A.Reason = 'loggedin')
  GROUP BY A.UserId, convert(varchar, A.Date, 102)
) A on B.Nordia_ID = A.UserId and A.adate = convert(varchar, B.StatusDateTime, 102)

答案 1 :(得分:0)

如果您需要关闭时间,请不要使用CONVERT。这样做:

DATEADD(dd,0,DATEDIFF(dd,0,A.DATE)) = DATEADD(dd,0,DATEDIFF(dd,0,B.StatusDateTime))

他们是约会,把它们视为日期,你不会因为将它们转换成字符串而遇到奇怪的错误。