0

我有一个简化的数据库,如下所示:

ID  |  SecondID   |  DateRecorded  |  NumberToCheck  |  NumberToUpdate

NumberToUpdate当前所有行的值为 0。

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

到目前为止我有

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.

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

我在这里忘记了什么?

非常感谢

4

2 回答 2

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
于 2012-06-18T17:31:21.463 回答
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 结合是唯一的,您的结构不能保证这一点。恐怕有了这种表格布局,就没有别的办法了。

于 2012-06-18T17:32:40.500 回答