简体   繁体   中英

Query previous row value and merge to current row

Is there a way how can I query the previous row value and merge to current row, here is my sample table scenario:

+-------------------------------------+
| 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 |
+-------------------------------------+

And my expected result should be this, just want to get the previous and current value and group it by selected columns and date.

+--------------------------------------------------+
| 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 |
+--------------------------------------------------+

any suggestions or solution, thanks in advance

Here is my actual query from my actual data as reference:

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

Hope I correctly got your question: 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM