MySQL8新特性-窗口函数

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

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

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

SELECT country,sum(sum)
FROM sales
GROUP BY country
order BY country;

窗口函数(以国家汇总)

select year,country,product,sum,
    sum(sum) over (PARTITION by country) as country_sum
 from sales
order by country,year,product,sum;

窗口函数(计算平局值)

select year,country,product,sum,
            sum(sum) over (PARTITION by country) as country_sum,
            avg(sum) over (PARTITION by country) as country_avg
 from sales
order by country,year,product,sum;

专用窗口函数:

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

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

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

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

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

窗口函数(排名)

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

SELECT
    YEAR,
    country,
    product,
    sum,
    row_number() over (ORDER BY sum) AS 'rank',
        rank() over (ORDER BY sum) AS 'rank_1'
FROM
    sales;

SELECT
    YEAR,
    country,
    product,
    sum,
    sum(sum) over (PARTITION by country order by sum rows unbounded preceding) as sum_1
FROM
    sales order by country,sum;

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

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

猜你喜欢

转载自blog.csdn.net/m0_70299172/article/details/130496398
今日推荐