美文网首页
postgreql 窗口函数用法

postgreql 窗口函数用法

作者: 护念 | 来源:发表于2017-12-30 15:59 被阅读0次

    认识窗口函数

    在说窗口函数之前我们先来看一个问题:
    假设我们有这样一张products表:


    Snip20171230_1.png

    我们想要同时取出产品的名称、售价,同时列出这件产品对应的商品类型的平均价格?
    按照以前我们的子查询知识我们可以这样:

    select name,
           price,
           (select avg(price) from products where type = p.type) as type_avg_price
    from products p;
    
    Snip20171230_2.png

    很好!能够正确执行,但窗口函数有更好的办法(可以先分类再算平均价格)

    select name,
           price,
           avg(price) over (partition by type) as type_avg_price
    from products;
    
    # partition by是按照什么分类的意思
    
    Snip20171230_3.png

    这也能很好的执行。

    下面让我们把问题难度加大,我们需要同时取出商品名称、价格、然后按照商品的价格在自己的品类中去排序。
    如果用普通的方法比较不好做了,但窗口函数有办法

    select name,
           price,
           row_number() over (partition by type order by price) as postition
    from products;
    
    # row_number是postgresql中的排序函数
    # 这里先分类,再排序
    
    Snip20171230_4.png

    窗口函数的语法

    函数  OVER (<PARTITION BY column_name> <ORDER BY column_name>)
    
    # 函数主要有两种:(sum avg min max)聚合函数、(rank、dense_rank、row_number)专用窗口函数
    # partition by 和 order by 都是可以省略的
    

    小结

    • 窗口函数的关键点在于,它可以先分类再做函数操作;
    • 对比于聚合函数,窗口函数具有聚合的同时保留其它列展示的功能,故称窗口。

    相关文章

      网友评论

          本文标题:postgreql 窗口函数用法

          本文链接:https://www.haomeiwen.com/subject/pcxngxtx.html