有没有办法查询上一行值并合并到当前行,这是我的示例表场景:
+-------------------------------------+
| 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 :(得分:0)
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;