2011-09-14 37 views
1

我有兩個表。使用MIN更新

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 

我需要更新表B與分鐘(a.starttime),同時a.Userid = b.userid,a.starttime = b.date於starttime,和原因= '登錄'。

我似乎在使用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具有的日期和時間。

+0

問題是什麼?語法問題?不正確的數據? –

+0

你忘了指定表別名嗎?它應該是'Min(A.starttime)',而不是'MIN(starttime)'。 – a1ex07

+0

問題是更新到b.starttime是所有相同的數據,而不是更新條件滿足的開始時間(日期匹配,用戶匹配,和原因=登錄) – Jessica

回答

4

如果你只是沒有得到正確的結果,可能是因爲你需要使用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) 
0

如果您需要剝離時間,請不要使用CONVERT。做到這一點,而不是:

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

他們是日期,像對待日期,你會不會從它們轉換爲字符串碰上古怪的錯誤。