模拟 MySQL 中的滞后函数

Simulate lag function in MySQL(模拟 MySQL 中的滞后函数)
本文介绍了模拟 MySQL 中的滞后函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

| 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.
    • 注意事项:

      1. order by 子句在这里很重要,就像在常规中一样窗函数.
      2. 您可能还想对 company 使用滞后,以确保您计算的是同一 company 的引号中的差异.
      3. 你也可以用同样的方式实现行计数器@cnt:=@cnt+1
      1. order by clause is important here just like it is in a regular window function.
      2. You might also want to use lag for company just to be sure that you are computing difference in quotes of the same company.
      3. You can also implement row counters in the same way @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 中的滞后函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

      本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)