| 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 中对这个表做滞后以打印引号中的差异,例如:
How do I do a lag on this table in MySQL to print the difference in quotes, for example:
GOOGLE | 20
SAP | 40
这是我最喜欢的 MySQL hack.
This is my favorite MySQL hack.
这是模拟滞后函数的方式:
This is how you emulate the lag function:
SET @quot=-1;
select time,company,@quot lag_quote, @quot:=quote curr_quote
from stocks order by company,time;
lag_quote 保存前一行引用的值.对于第一行,@quot 是 -1.curr_quote 保存当前行的引用值.
lag_quote holds the value of previous row's quote. For the first row @quot is -1.curr_quote holds the value of current row's quote.注意事项:
order by 子句在这里很重要,就像在常规中一样窗函数.company 使用滞后,以确保您计算的是同一 company 的引号中的差异.@cnt:=@cnt+1order by clause is important here just like it is in a regular
window function. company just to be sure that you are computing difference in quotes of the same company.@cnt:=@cnt+1与使用聚合函数、存储过程或在应用服务器中处理数据等其他一些方法相比,这种方案的优点是计算量非常小.
The nice thing about this scheme is that is computationally very lean compared to some other approaches like using aggregate functions, stored procedures or processing data in application server.
现在来解决以您提到的格式获取结果的问题:
Now coming to your question of getting result in the format you mentioned:
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;
嵌套是不相关的,所以没有它看起来(语法上)那么糟糕(计算上):)
The nesting is not co-related so not as bad (computationally) as it looks (syntactically) :)
如果您需要任何帮助,请告诉我.
Let me know if you need any help with this.
这篇关于模拟 MySQL 中的滞后函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何有效地使用窗口函数根据 N 个先前值来决定How to use windowing functions efficiently to decide next N number of rows based on N number of previous values(如何有效地使用窗口函数根据
在“GROUP BY"中重用选择表达式的结果;条款reuse the result of a select expression in the quot;GROUP BYquot; clause?(在“GROUP BY中重用选择表达式的结果;条款?)
Pyspark DataFrameWriter jdbc 函数的 ignore 选项是忽略整Does ignore option of Pyspark DataFrameWriter jdbc function ignore entire transaction or just offending rows?(Pyspark DataFrameWriter jdbc 函数的 ig
使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 Error while using INSERT INTO table ON DUPLICATE KEY, using a for loop array(使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 for 循环数组
pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合pyspark mysql jdbc load An error occurred while calling o23.load No suitable driver(pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合适的
如何将 Apache Spark 与 MySQL 集成以将数据库表作为How to integrate Apache Spark with MySQL for reading database tables as a spark dataframe?(如何将 Apache Spark 与 MySQL 集成以将数据库表作为