使用最小日期更新临时表

时间:2012-11-26 15:38:08

标签: sql sql-server-2008 tsql

我正在尝试更新InsertDate表中所有不同AccIdAccNameHolder组合的#tmpResults,前提是存在较早的插入日期。

表模式如下:

#tmpResults

Trans | AccId | AccountNameHolder | EarlyDate | CardType 

PositionCollection

Id | AccId | InsertDate | BtchId

卡错误

AccId | AccNameHolder | BtchId | TransId

这是我到目前为止所尝试的内容:

UPDATE  RES  
SET     EarlyDate = pc.InsertDate   
FROM  ( dbo.PositionCollection pc    
        LEFT JOIN dbo.CardErrors ce ON ce.BtchId = pc.BtchId AND pc.id =     ce.Transid  )    
    INNER JOIN #tmpResults RES   
ON      RES.AccId = pc.AccId    
AND     RES.AccNameHolder = ce.AccNameHolder    
WHERE   RES.EarlyDate = (SELECT MIN(InsertDate) FROM PostionCollection)    
AND     RES.AccId = pc.AccId    
AND     RES.AccNameHolder = ce.AccNameHolder

2 个答案:

答案 0 :(得分:0)

下面是一些更通用的解决方案,对于InsertDate为null的地方,您可以将它们与DateDiff一起使用,将条件更改为更早,更晚或任何类似

的条件
OldInstDate <= COALESCE(NewInstDate, OldInstDate)

条件更新可以在select语句中实现,所以......

SET InsertDate = COALESCE(InsertDate, NewInsertDate) WHERE...

OR

SET InsertDate = CASE WHEN InsertDate IS NULL THEN NewInsertDate 
                      ELSE InsertDate END

OR

WHERE ...
AND InsertDate IS NULL

对于子查询的真正明确帮助 http://allenbrowne.com/subquery-01.html 我认为这可能是我见过的最好的http://allenbrowne.com/subquery-02.html用于解决问题

答案 1 :(得分:0)

在UPDATE语句中使用派生表

UPDATE x
SET x.EarlyDate = x.InsertDate  
FROM  ( 
       SELECT RES.EarlyDate, pc.InsertDate
       FROM dbo.PositionCollection pc
         LEFT JOIN dbo.CardErrors ce ON ce.BtchId = pc.BtchId AND pc.id = ce.Transid
         INNER JOIN #tmpResults RES ON RES.AccId = pc.AccId
           AND RES.AccNameHolder = ce.AccNameHolder
       WHERE RES.EarlyDate = (SELECT MIN(InsertDate) FROM PostionCollection) AND RES.AccId = pc.AccId
         AND RES.AccNameHolder = ce.AccNameHolder
       ) x

更新27.11.2012

UPDATE x
SET x.EarlyDate = x.InsertDate
FROM  (
       SELECT RES.EarlyDate, m.InsertDate
       FROM dbo.PositionCollection pc
         LEFT JOIN dbo.CardErrors ce ON ce.BtchId = pc.BtchId AND pc.id = ce.Transid
         INNER JOIN #tmpResults RES ON RES.AccId = pc.AccId AND RES.AccNameHolder = ce.AccNameHolder
         INNER JOIN (SELECT MIN(InsertDate) AS InsertDate FROM PostionCollection) m
           ON RES.EarlyDate = m.InsertDate 
       ) x