如何将相同的多窗口函数组合为一个,并在查询中的任何需要的位置调用别名?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将相同的多窗口函数组合为一个,并在查询中的任何需要的位置调用别名?相关的知识,希望对你有一定的参考价值。
如何解决在单个SQL查询中针对不同聚合多次使用相同窗口函数的问题?有没有什么方法可以对它进行别名并根据需要在查询中多次调用它。
我尝试使用'Window'子句,但SQL Server目前不支持'Window'子句。
select empid, qty,
sum(qty) over (partition by empid order by month rows between unbounded preceding and current row) as running_sum,
avg(qty) over (partition by empid order by month rows between unbounded preceding and current row) as running_avg,
min(qty) over (partition by empid order by month rows between unbounded preceding and current row) as running_min,
max(qty) over (partition by empid order by month rows between unbounded preceding and current row) as running_max
from employee
有没有办法删除代码中的冗余?
答案
不在SQL Server中,ANSI SQL支持用于定义可以重用的窗口的WINDOWS
子句。但是,SQL Server不支持它。
我认为你可以略微简化你的逻辑:
select empid, qty,
sum(qty) over (partition by empid order by month) as running_sum,
avg(qty) over (partition by empid order by month) as running_avg,
min(qty) over (partition by empid order by month) as running_min,
max(qty) over (partition by empid order by month) as running_max
from employee;
以上是关于如何将相同的多窗口函数组合为一个,并在查询中的任何需要的位置调用别名?的主要内容,如果未能解决你的问题,请参考以下文章