2017-04-26 147 views
0

有沒有一種方法,我怎麼可以查詢以前的行值,併合併到當前行,這裏是我的示例表場景:查詢以前的行值,併合併到當前行

+-------------------------------------+ 
| ColA | ColB | ColValue | Date | 
|------|------|----------|------------| 
| AAA | 111 |  5 | 2017-04-23 | 
| AAA | 111 |  4 | 2017-04-22 | 
| AAA | 111 |  3 | 2017-04-21 | 
| BBB | 222 |  5 | 2017-04-30 | 
| BBB | 222 |  4 | 2017-04-29 | 
+-------------------------------------+ 

而我預期的結果應該是這只是想獲得以前和當前值,並按選定的列和日期進行分組。

+--------------------------------------------------+ 
| ColA | ColB | PreValue | CurValue | Date | 
|------|------|----------|-------------------------| 
| AAA | 111 |  4 |  5  | 2017-04-23 | 
| AAA | 111 |  3 |  4  | 2017-04-22 | 
| AAA | 111 | N/A |  3  | 2017-04-21 | 
| BBB | 222 |  4 |  5  | 2017-04-30 | 
| BBB | 222 | N/A |  4  | 2017-04-29 | 
+--------------------------------------------------+ 

任何建議或解決方案,在此先感謝

下面是從我的實際數據作爲參考我的實際查詢:

SELECT ai.APName, tbap.Value , tbap.DateTime, tbap.Comment, tbap.ModifiedBy, tbap.ToolName, d.Name as Strategy FROM (SELECT dt.*,ins.Value as ToolName FROM (SELECT av.*,ai.DocumentID,ai.IndexID FROM ControlAutomation.appartitionindexes ai 
JOIN (SELECT * FROM ControlAutomation.appartitionvalues 
where DateTime > '2017-04-22 23:17:13' and DateTime < '2017-04-26 23:18:28') av 
ON ai.APPartitionID = av.APPartitionID) dt INNER JOIN factory.indexes ins ON ins.ID = dt.IndexID 
where dt.comment like '%updateAdjustableParameter%' 
group by dt.ID) tbap 
INNER JOIN ControlAutomation.documents d ON d.ID = tbap.DocumentID 
INNER JOIN appartitionindexes ai ON ai.APPartitionID = tbap.APPartitionID 
GROUP BY tbap.ID 
ORDER BY tbap.ToolName DESC, d.Name, tbap.DateTime DESC 
LIMIT 100 
+0

表中有主鍵嗎?或者換句話說要知道哪個是以前的價值。由於給定的示例表AAA具有全部第23個日期,因此無法知道哪個是第一個 –

+0

爲什麼需要此輸出,這可能需要使用會話變量? –

+0

實際上,在我的真實數據中,日期列是唯一的,我將它用作我的主要數據,所以這就是爲什麼它需要先按日期進行分組,然後是colA然後colB –

回答

0

希望我正確地得到了你的問題:http://sqlfiddle.com/#!9/d815c/6

select 
    prev_query.cola as ColA, 
    prev_query.colb as ColB, 
    rhs.colvalue as PreValue, 
    prev_query.colvalue as CurValue, 
    prev_query.coldate as ColDate 
from 
    prev_query left join prev_query as rhs 
    on prev_query.cola = rhs.cola 
    and prev_query.colb = rhs.colb 
    and prev_query.colvalue = rhs.colvalue + 1 
order by 
    prev_query.cola, prev_query.colb, prev_query.coldate desc; 
+0

我很欣賞這個解決方案,但在得到我的結果之前它來自不同的表格。我想創建它作爲視圖,但我沒有任何管理權限的數據庫,所以我用它作爲子查詢。當試圖做你的左連接給我,該表不存在。 –

+0

我更新了我的問題併發布了我的實際查詢,並努力將您的邏輯注入到我的查詢中,希望將有助於作爲參考,並且它只着重於tbap.Value列。 –

+0

@ Rockn'Roll你可以提供一個工作sqlfiddle與一些數據? –