子查询作为偏移参数 - DB2 中 LAG() 函数的替代方案

发布于 2025-01-09 05:42:03 字数 749 浏览 0 评论 0原文

我想问你一个问题。一般来说,我们知道LAG()函数可以用LAG(列表达式, Offset, [默认值]) OVER (ORDER BY ...)来表示。偏移量不能是 DB2 中的子查询。有谁知道db2中的函数与LAG()具有相同的功能,并且它可以将子查询或计算字段作为偏移量参数 这是在上一步中从源的子查询中计算出来的?

所以情况如下,我想使用滞后函数,但偏移量参数 LAG(列表达式, 偏移量,[默认值]) OVER(ORDER BY . . .) 不是一个常数值。

例如我有:

LAG(CAST(DATE_utc AS VARCHAR), 抵消, 0) OVER(按 ID 分区, ID_2 按 DATE_utc 排序) AS PREV 来自
( SELECT , CAST(计数(fid) OVER(按 f|| t 分区,ID, ID_2) AS INTEGER) AS 偏移量 来自 SCHEMA.TABLE_1 其中 ID = 65020475 ) AS inside_dataset

如您所见,[offset] 是根据 TABLE_1 计算得出的,并用作外部层 LAG 函数的参数。 但是,这会导致以下错误: SQL 错误 [42815]:未处理该语句,因为参数的数据类型、长度或值 例程“LAG”的位置“2”不正确。是否有其他替代方案?

先感谢您!

I would like to ask you a question. Generally, we know that LAG() function can be expressed us LAG(column expression, Offset, [defaul value]) OVER (ORDER BY ...). The offset can't be a subquery in DB2. Does anyone know a function in db2 that has the same functionality with LAG() and it can take as an offset argument a subquery or a calculated field that is calculated in the previous step in a subquery from the source?

So the case is as follows, I want to use lag function but the offset argument LAG(column expression, offset,[default value]) OVER(ORDER BY . . .)
is not a constant value.

For example I have:

LAG(CAST(DATE_utc AS VARCHAR),
offset,
0)
OVER (PARTITION BY ID,
ID_2 ORDER BY DATE_utc) AS PREV
FROM
(
SELECT , CAST(count(fid)
OVER (PARTITION BY f|| t, ID,
ID_2) AS INTEGER) AS offset
FROM SCHEMA.TABLE_1
WHERE ID = 65020475
)
AS inner_dataset

As you can see the [offset] is calculated from the TABLE_1 and is used as a parameter on the LAG function on the outer level.
However, this results in the following error:
SQL Error [42815]: The statement was not processed because the data type, length or value of the argument for the parameter
in position "2" of routine "LAG" is incorrect.
Is there any alternative to this?

Thank you in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒绊 2025-01-16 05:42:03

您可以使用 row_number() 和自联接,如下所示:

with tt (a, rn) as (
    select a, row_number() over (order by a) as rn from t
) 
select t1.a, t2.a as lag_a, t1.rn, t2.rn 
from tt t1
left join tt t2
   on t2.rn = t1.rn - (select max(x) from p);

改进的穿刺器小提琴

You can use row_number() and a self join as in:

with tt (a, rn) as (
    select a, row_number() over (order by a) as rn from t
) 
select t1.a, t2.a as lag_a, t1.rn, t2.rn 
from tt t1
left join tt t2
   on t2.rn = t1.rn - (select max(x) from p);

Modified Impalers Fiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文