| time | company | quote | +---------------------+---------+-------+ | 0000-00-00 00:00:00 | GOOGLE | 40 | | 2012-07-02 21:28:05 | GOOGLE | 60 | | 2012-07-02 21:28:51 | SAP | 60 | | 2012-07-02 21:29:05 | SAP | 20 |
如何在MySQL中的此表上做滞后处理以打印引号中的差异,例如:
GOOGLE | 20 SAP | 40
这是我最喜欢的MySQL hack。
这是模拟滞后函数的方式:
SET @quot=-1; select time,company,@quot lag_quote, @quot:=quote curr_quote from stocks order by company,time;
lag_quote
curr_quote
笔记:
order by
company
@cnt:=@cnt+1
与该方案相比,与使用聚合函数,存储过程或在应用程序服务器中处理数据等其他方法相比,该方案在计算上非常精益。
编辑:
现在开始以您提到的格式获取结果的问题:
SET @quot=0,@latest=0,company=''; select B.* from ( select A.time,A.change,IF(@comp<>A.company,1,0) as LATEST,@comp:=A.company as company from ( select time,company,quote-@quot as change, @quot:=quote curr_quote from stocks order by company,time) A order by company,time desc) B where B.LATEST=1;
嵌套不是相互关联的,因此(在计算上)不如在语法上看起来那么糟糕:)
让我知道您是否需要任何帮助。