按日期顺序更新表

时间:2014-06-03 11:16:47

标签: sql sql-order-by

如何按日期顺序更新表,我有一个日期字段,TransactionDate,一些列值依赖于以前的值,如何通过表来更新日期顺序。

我已经尝试过一些东西,但仍然遇到“ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP或FOR XML。”

我有要重新处理的日期范围,更改较旧的值意味着重新计算较新的值。

UPDATE M
SET M.AvgGain = CASE WHEN M.Price > Previous.Price THEN ( ISNULL( Previous.AvgGain * 13.0, 0 ) + ( M.Price - Previous.Price )) / 14.0 ELSE  ( ISNULL( Previous.AvgGain * 13.0, 0 ) / 14.0 )END
FROM SalesData M
JOIN SalesData AS Previous ON ( SELECT TOP 1 PK FROM SalesData WHERE AbbrevID = M.AbbrevID AND TransactionDate < M.TransactionDate ORDER BY TransactionDate DESC) = Previous.PK
WHERE M.AbbrevID IN ( SELECT PK FROM SalesData  WHERE AbbrevID = ( SELECT PK FROM SalesPeople WHERE Abbreviation = 'Fred') ) AND TransactionDate BETWEEN '1996-02-23' and '1996-05-08'

当我通过TransactionDate将订单插入加入时,它对我很生气

3 个答案:

答案 0 :(得分:3)

如果你需要一次迭代一行,我可能会使用游标:

DECLARE @c_mem INT -- for example some numbeer of day, ie the calcuation you need to make from previous rows
SET @c_mem = 0 -- some initial value

DECLARE db_cursor CURSOR FOR  
SELECT [your_table_UID_field]
FROM [your_table_name]
ORDER BY TransactionDate

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @c_uid  

WHILE @@FETCH_STATUS = 0  
BEGIN  
       SET @c_mem=[some calculation based on c_mem itself and the current transac date]
       UPDATE [your_table_name]
       SET TransactionDate=[some calculation based on @c_mem, eg transac date + c_mem days]
       WHERE [your_table_UID_field]=@c_uid;

       FETCH NEXT FROM db_cursor INTO @c_uid  
END  

CLOSE db_cursor  
DEALLOCATE db_cursor 

这是你要找的吗?

答案 1 :(得分:0)

尝试使用CROSS APPLY

UPDATE    M
    SET M.AvgGain = CASE WHEN M.Price > Previous.Price THEN 
                        ( ISNULL( Previous.AvgGain * 13.0, 0 ) + ( M.Price - Previous.Price )) / 14.0 
                    ELSE  
                        ( ISNULL( Previous.AvgGain * 13.0, 0 ) / 14.0 )
                    END
FROM    SalesData AS M
        CROSS APPLY (
            SELECT    TOP 1 AvgGain, Price
            FROM      SalesData
            WHERE     AbbrevID = M.AbbrevID AND TransactionDate < M.TransactionDate 
            ORDER BY TransactionDate DESC
        ) AS Previous
WHERE    M.AbbrevID IN ( 
                    SELECT     PK 
                    FROM     SalesData  
                    WHERE     AbbrevID = ( SELECT PK FROM SalesPeople WHERE Abbreviation = 'Fred')      
                )
        AND TransactionDate BETWEEN '1996-02-23' and '1996-05-08' 

答案 2 :(得分:-1)

在SQL server SQL2005 +中,您可以使用更新表&#39; order by&#39;通过使用&#39;和&#39; over&#39;,如下所示:

With XYX As
(
  SELECT id,Field2, ROW_NUMBER() 
           OVER (ORDER BY YourDateField DESC) AS RN
  FROM YourTable
)
UPDATE XYX SET Field2=RN

reference