2013-07-24 28 views
0

我试图发布完整的SQL代码来引导您完成数据和转换,但它不会在此处发布。长话短说,我结束了这样一个数据表:SQL游标在类别上?

Location Date      Direction PreviousDirection Offset 
site1  2013-07-22 11:30:45.000 302  302    0 
site1  2013-07-22 11:31:45.000 322  302    20 
site1  2013-07-22 11:32:45.000  9  322    47 
site1  2013-07-22 11:33:45.000  9   9    0 
site1  2013-07-22 11:34:45.000  0   9    -9 
site2  2013-07-22 11:30:45.000 326  326    0 
site2  2013-07-22 11:31:45.000  2  326    36 
site2  2013-07-22 11:32:45.000  2   2    0 
site2  2013-07-22 11:33:45.000  2   2    0 
site2  2013-07-22 11:34:45.000  2   2    0 

位置,日期是主键。我需要帮助生成[AdjustedDirection]列,计算方法如下:

对于第一行(对于每个位置,例如site1,site2):由于没有上一行要计算,AdjustedDirection =第一行的方向。

之后,第二行AdjustedDirection:它是第一行的AdjustedDirection加第二行的偏移量。 第三行AdjustedDirection:这是第二行的AdjustedDirection加上第三行的偏移量。 等等......

我认为这需要一个游标,但我不知道在多个类别(位置)上执行游标的语法和/或可能有不同的答案。我无法描述这个步骤需要多少步骤和过程是多么复杂。我非常接近结束,完全卡在这里!

如果任何人有线索如何填充这些AdjustedDirection值,请证明你的迷人。谢谢!!

结果应该是这样的(日期截断间距,显示了如何当前行的清晰度调整之前的调整方向计算):

Location Date  Direction Offset PrevAdjDirection AdjustedDirection 
site1  11:30:45.000 302   0   302    302 
site1  11:31:45.000 322   20   302    322 
site1  11:32:45.000  9   47   322    369 
site1  11:33:45.000  9   0   369    369 
site1  11:34:45.000  0   -9   369    360 
site2  11:30:45.000 326   0   326    326 
site2  11:31:45.000  2   36   326    362 
site2  11:32:45.000  2   2   362    362 
site2  11:33:45.000  2   2   362    362 
site2  11:34:45.000  2   2   362    362 

的感谢!

+2

请使用标签来标识SQL Server的版本。此外,不要用单词问题来描述所需的结果,而要显示所需的调整后的数据作为查询的结果。 –

回答

1

这是一个使用相关子查询的解决方案,其中一些可以被窗口函数替换(SQL Server的版本在这里有所不同)。

你想改变你的逻辑。等效的逻辑是:

  1. 对于第一行,使用方向
  2. 对于后续的行,可使用不包括所述第一偏移加上从第一行方向上的偏移的累积和。

下面使用相关子计算相应的变量,然后用简单的逻辑组合它们:

select t.*, 
     FirstOffset + coalesce(SumEarlierOffsets - FirstOffset + Offset, 0) as AdjustedOffset 
from (select t.*, 
      (select Direction 
       from t t2 
       where t2.location = t.location 
       order by date asc 
      ) as FirstDirection, 
      (select SUM(offset) 
       from t t2 
       where t2.location = t.location and 
        t2.date < t.date 
      ) as SumEarlierOffsets, 
      (select Offset 
       from t t2 
       where t2.location = t.location 
       order by date asc 
      ) as FirstOffset 
     from t 
    ) t 
0

我结束了当前的数据转储到一个临时表,做一个WHILE UPDATE这样

SELECT Location, Date, Direction, Offset, Adjusted = NULL 
INTO #results 
FROM t1 

WHILE (
SELECT COUNT(*) FROM #results WHERE Adjusted IS NULL 
) > 0 
UPDATE TOP (1) t1 
SET Adjusted = ISNULL(t2.Adjusted,ISNULL(t2.Direction,t1.Direction)) + t1.Offset 
FROM #results t1 
LEFT JOIN #results t2 ON t2.Location = t1.Location AND t2.Date =  DateAdd(minute,-1,t1.Date) 
WHERE t1.Adjusted IS NULL 

感谢您的意见和灵感!