当前位置:   article > 正文

MySQL8新特性-窗口函数_mysql8 分析函数

mysql8 分析函数

MySQL 8.0支持窗口函数(Window Function),也称分析函数。窗口函数与分组聚合函数类似,但是每一行数据都生成一个结果。聚合窗口函数: SUM /AVG / COUNT /MAX/MIN等等。

案例如下:sales表结构与数据如下:

普通的分组、聚合(以国家统计)

  1. SELECT country,sum(sum)
  2. FROM sales
  3. GROUP BY country
  4. order BY country;

窗口函数(以国家汇总)

  1. select year,country,product,sum,
  2. sum(sum) over (PARTITION by country) as country_sum
  3. from sales
  4. order by country,year,product,sum;

窗口函数(计算平局值)

  1. select year,country,product,sum,
  2. sum(sum) over (PARTITION by country) as country_sum,
  3. avg(sum) over (PARTITION by country) as country_avg
  4. from sales
  5. order by country,year,product,sum;

专用窗口函数:

  • 序号函数:ROW_NUMBER()、RANK()、DENSE_RANK()

  • 分布函数:PERCENT_RANK()、CUME_DIST()

  • 前后函数:LAG()、LEAD()

  • 头尾函数:FIRST_VALUE()、LAST_VALUE()

  • 其它函数:NTH_VALUE()、NTILE()

窗口函数(排名)

用于计算分类排名的排名窗口函数,以及获取指定位置数据的取值窗口函数

  1. SELECT
  2. YEAR,
  3. country,
  4. product,
  5. sum,
  6. row_number() over (ORDER BY sum) AS 'rank',
  7.       rank() over (ORDER BY sum) AS 'rank_1'
  8. FROM
  9. sales;

  1. SELECT
  2. YEAR,
  3. country,
  4. product,
  5. sum,
  6. sum(sum) over (PARTITION by country order by sum rows unbounded preceding) as sum_1
  7. FROM
  8. sales order by country,sum;

当然可以做的操作很多,具体见官网:

https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/702218
推荐阅读
相关标签
  

闽ICP备14008679号