更新时间:2023-01-22 16:40:14
如果您有一个附加的序列列(例如UniqeID),这将很容易.如果有的话,就可以这样更新 CumulativeTable SET 累积=值+(选择 Sum(Value)从累积表其中 UniqueID< c.UniqueID AND ID = c.ID) 来自 CumulativeTable c
或者如果没有,可以尝试一下,DECLARE @ TempTable TABLE (唯一ID int IDENTITY , ID int , 值数字( 18 , 3 ), 累积数字( 18 , 3 ) ) DECLARE @ TempTable TABLE (唯一ID int IDENTITY , ID int , 值数字( 18 , 3 ), 累积数字( 18 , 3 ) ) 插入 插入 @ TempTable (ID,值,累计) 选择 ID,值,累积从累积表 更新 CumulativeTable SET 累积= COALESCE (c.Value +( Select Sum(Value)来自 @ TempTable 其中 UniqueID< c.UniqueID AND ID = c.ID), 0 ) 来自 CumulativeTable t, @ TempTable c 位置 t.ID = c.ID AND t.Value = c.Value
但是如果您有多个具有相同ID和值的记录,这将无法为您提供正确的值lockquote>Hi,
I am having trouble writing a query that accurately does what I need.
I have a table like the followingId Date Value Cumulative 1 Jan 1st 0.2 2 Jan 1st 0.5 1 Jan 2nd 0.7 2 Jan 2nd 0.6 4 Jan 2nd 0.1 1 Jan 3rd 0.02 3 jan 3rd 0.01 4 Jan 3rd 0.03
I want to write a query which inserts the cumulative column with the sum of the value for the same Ids i.e.,Id Cumulative 1 0.2 2 0.5 1 0.9 (0.2+0.7) 2 1.1 (0.5+0.6) 4 0.1 1 0.92 (0.2+0.7+0.02) 3 0.01 4 0.13 (0.1 + 0.03)
Thanks in advance.It would be easy if you have an additional sequence column (e.g. UniqeID). If you have, you can just have it this wayUpdate CumulativeTable SET Cumulative = Value + (Select Sum(Value) From CumulativeTable Where UniqueID < c.UniqueID AND ID = c.ID) From CumulativeTable c
or if you don''t have, you can try this,DECLARE @TempTable TABLE (UniqueID int IDENTITY, ID int, Value numeric(18,3), Cumulative numeric(18,3) ) DECLARE @TempTable TABLE (UniqueID int IDENTITY, ID int, Value numeric(18,3), Cumulative numeric(18,3) ) Insert Into @TempTable (ID, Value, Cumulative) Select ID, Value, Cumulative From CumulativeTable Update CumulativeTable SET Cumulative = COALESCE(c.Value + (Select Sum(Value) From @TempTable Where UniqueID < c.UniqueID AND ID = c.ID),0) From CumulativeTable t, @TempTable c Where t.ID = c.ID AND t.Value = c.Value
but this will not give you correct value if you have multiple records with the same ID and value