更新具有相同标识符的最早日期的列,并且列具有> 0

时间:2012-06-18 17:21:41

标签: sql sql-server sql-server-2008

我有一个数据库,其简化如下:

ID  |  SecondID   |  DateRecorded  |  NumberToCheck  |  NumberToUpdate

NumberToUpdate目前所有行的值都为0。

我希望使用同一行NumberToUpdate的值更新NumberToCheck,减去最早NumberToCheckDateRecorded (Min(DateRecorded)的值“其中NumberToCheck大于0,并且与原始行具有相同的ID和secondID。

到目前为止我已经

UPDATE dbo.Table
SET NumberToUpdate =//Update NumberToUpdate
   NumberToCheck - //NumberToCheck from the current row, subtracting...
      (SELECT TOP 1 t2.NumberToCheck FROM Table t2 WHERE ID = t2.ID AND secondID = t2.secondID AND t2.DateRecorded = 
      (SELECT TOP 1 MIN(t3.DateRecorded) FROM Table t3  WHERE t2.ID = t3.ID AND t2.secondID = t3.secondID AND t3.Passes > 0))
      //the NumberToCheck with the earliest date, of the same ID.

然而,这是不正确的,并且正在返回没有意义的值(包括不应该有的负值!)

我忘记了什么?

非常感谢

2 个答案:

答案 0 :(得分:1)

首先,您应该从选择查询开始,以获得所需的值:

select t.*
from (select t.*, row_number() over (partition by id order by date) as seqnum
      from table t
      where number_to_check > 0
     ) t
where seqnum = 1

现在,您可以在原始更新中使用它:

with vals as (select t.*
              from (select t.*, row_number() over (partition by id order by date) as seqnum
                    from table t
                    where NumberToCheck > 0
                   ) t
              where seqnum = 1
             )
update table
    set NumberToUpdate = NumberToCheck - vals.NumberToCheck
from vals
where t.id = vals.id

答案 1 :(得分:0)

UPDATE dbo.Table as t1
INNER JOIN
(
  SELECT MIN(DateRecord) as mindate, ID
  FROM dbo.Table
  GROUP BY ID
) as mindates
ON t1.ID = mindates.ID
INNER JOIN
dbo.Table as substractions
ON mindates.mindate = substraction.DateRecord
AND mindates.ID = substraction.ID
SET t1.numberToUpdate = t1.numberToCheck - substractions.NumberToCheck
WHERE substraction.NumberToCheck > 0
--your questions is ambigious here: did you mean this one should be greater than 0, or should t1.NumberToCheck > 0 ?
AND t1.DateRecord <> mindates.mindate
--Assuming that you don't want to update the record with the lowest date.

注意: 这假设DateRecord与ID结合是唯一的,您的结构无法保证。我担心这种表布局没有别的办法。