2012-08-25 65 views
2

我收到了一張隨時間變化的表格。該表格包含很多行,不能在格式中更改。 每個位置都插入一個id,實際位置和時間戳(日期時間)。該位置本身插入連接的字符串中,可以使用自定義函數將其轉換爲x/y座標。計算與前一行數據的差異

我想創建一個過程,並列出某個特定的所有已知位置及其適當的時間戳。到目前爲止沒有問題。但也希望創建一個表示位置和時間差異的輸出列。

澄清。我有什麼:

Id | Timestamp   | Foreign_Id | POS    
---------------------------------------------------------- 
1 | 2011-02-20 00:00:00 |  2  | PositionAsString 
---------------------------------------------------------- 
2 | 2011-02-20 00:00:05 |  2  | PositionAsString 
---------------------------------------------------------- 
3 | 2011-02-20 00:00:15 |  2  | PositionAsString 
---------------------------------------------------------- 
4 | 2011-02-20 00:00:37 |  2  | PositionAsString 

的位置的座標是通過這爲X和Y. 的位置差將利用勾股定理計算返回浮點值的功能getXgetY可用的,因爲它是唯一的2D 。

我想

Id | Timestamp   | Foreign_Id | POS    | DiffPos | Speed 
--------------------------------------------------------------------------- 
1 | 2011-02-20 00:00:00 |  2  | PositionAsString | 0  | 0  
--------------------------------------------------------------------------- 
2 | 2011-02-20 00:00:05 |  2  | PositionAsString | 20 | 4  
--------------------------------------------------------------------------- 
3 | 2011-02-20 00:00:10 |  2  | PositionAsString | 10 | 2  
--------------------------------------------------------------------------- 
4 | 2011-02-20 00:00:20 |  2  | PositionAsString | 10 | 1  

什麼,所以現在我的問題是如何計算的差異上一行。 重要的是,結果集被縮小到外鍵,因爲表中有很多行,所以執行不必要的計算。

回答

-1

感謝您的建議,但因爲這是複雜的,我現在用的另一種解決方案效率低下。正如我上面所述,我無法更改源表的格式。但是可能的是修改寫入該跟蹤表的觸發器,以便在插入新行之前計算差異。

這當然不適用於現有的條目,但這是可以接受的。

-1

您可以選擇數據並遍歷結果集,然後進行計算。 ,同時這樣做,請確保您爲所需的foreign_id選擇數據,並確保按時間戳排序結果。

因此,例如:

select pos 
from my_table 
where Foreign_Id=2 
order by Timestamp 

現在你可以遍歷你想要的數據和打印。第一行將始終顯示0,從第二行開始,您可以計算數據。您可以存儲當前行的數據,以便在讀取另一行時進行比較。

我從來沒有在我的SQL中使用過程,所以我不熟悉要使用的語法。 但在步驟(你可以編寫)自由文本描述:

1- define a variable previous_pos and another one current_pos, initially both are empty or null. 

loop over the results from the result set reading one after the other. 
2- for each one you read, set current_pos to have the value of pos 
2- calculate the needed info: if previous_pos is empty you return 0 (will happen in first line only), else you calculate the data from current_pos and previous_pos 
3- print, save, or what ever you want with the calculated data 
3- set previous_pos to be equal to current_pos. 
4- loop again