Sql 使用窗口功能动态选择任意n列
我的real select语句摘要:Sql 使用窗口功能动态选择任意n列,sql,postgresql,Sql,Postgresql,我的real select语句摘要: select lag(somecol) over (partition by thing_id) as prev_1, lag(somecol,2) over (partition by thing_id) as prev_2, lag(somecol,3) over (partition by thing_id) as prev_3, othercol, ... 在实际查询中,上的要复杂得多,这会导致相当密集的、不可读的代码。此外,
select
lag(somecol) over (partition by thing_id) as prev_1,
lag(somecol,2) over (partition by thing_id) as prev_2,
lag(somecol,3) over (partition by thing_id) as prev_3,
othercol,
...
在实际查询中,上的要复杂得多,这会导致相当密集的、不可读的代码。此外,获取最后3行是硬编码的(vs n=任意值)
在straight SQL中,是否有任何方法可以迭代或递归地指定这些prev_x
列,以便1)代码更具可读性,2)可以动态指定prev cols的数量n?为了回答第一个问题,使代码更具可读性,Postgres允许定义窗口,命名它,然后在查询中多次引用它
有关以下内容,请参阅文档:
当查询涉及多个窗口函数时,可以
用一个单独的OVER子句写出每一条,但这是
如果需要相同的窗口行为,则会重复且容易出错
用于多个功能。相反,可以命名每个窗口行为
在WINDOW子句中,然后在OVER中引用。例如:
SELECT sum(salary) OVER w, avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);
我不知道这个特性是否是SQL标准的一部分,但我知道SQL Server不支持它
因此,您的查询如下所示:
select
lag(somecol) over w as prev_1,
lag(somecol,2) over w as prev_2,
lag(somecol,3) over w as prev_3,
othercol,
...
from
...
WINDOW w AS (partition by thing_id)
;
关于第二个问题,如何“动态指定prev cols的数量n”,您需要动态生成SELECT
语句的文本来实现这一点。RDBMS采用稳定的模式,即表和查询中的列数通常是固定的,而不是动态的。这解决了可读性问题,现在好多了。我无法动态生成SELECT,因此我将接受列计数的“硬编码”。