【问题标题】:Windowing function in My-Sql does not work as expectedMy-Sql 中的窗口化功能无法按预期工作
【发布时间】:2021-03-18 02:32:44
【问题描述】:

我在一个 my-sql 表中有三列:Id、name 和 mark。所有行彼此不同。 我使用下面的 sql 语句。在窗口函数内部,我不在两个 SQL 语句中使用 order by。我只有分区和范围框架。

理想情况下,它们应该在窗口函数的派生列下给出相同的结果;但是第一个总是在窗口下给出最大标记;而第二个比较前一行和当前行+1并给出预期结果。第一个真的很奇怪,即使我给出了无限的前行和当前行;实际上,它考虑的是整个窗口而不是给定的框架。

有人可以帮忙吗。

声明 1:

select  *
       ,max(mark) over( partition by name   rows between unbounded preceding and current row) as w_f 
from  ( select * from student order by name, mark asc) a

声明 2:

select  *
       ,max(mark) over( partition by name   rows between 1 preceding and 1 following) as w_f 
from  ( select * from student order by name, mark asc) a

【问题讨论】:

    标签: mysql sql max aggregate-functions window-functions


    【解决方案1】:

    没有order by 子句的行(或范围)框架没有意义:如果您不指定应使用哪些列进行排序,如何定义哪一行在前或后。

    还请注意,order by 子句的子查询可能不会按照您的预期进行。不能保证内部排序会传播到外部查询。

    在没有样本数据和预期结果的情况下,您实际上想要做什么有点不清楚。假设您有排序列 id,第一个查询将表述为:

    select s.*,
        max(mark) over(partition by name rows order by id) as w_f 
    from student
    order by name, id
    

    rows between unbounded preceding and current row 是默认窗口规范(实际上是range between ...,如果您有唯一的排序键,则等效)。

    第二个查询是这样的:

    select s.*,
        max(mark) over(partition by name rows order by id rows between 1 preceding and 1 following) as w_f 
    from student
    order by name, id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多