gpt4 book ai didi

mysql - 如何在 MySQL 中将 IFNULL 与窗口函数一起使用

转载 作者:行者123 更新时间:2023-11-29 02:41:20 25 4
gpt4 key购买 nike

如何将 ifnull 与窗口函数一起使用?

假设我在下面有这个查询结果,lag1 只是使用窗口函数向下移动的预算列,因此,该值为空。但我想用零替换该空值,以便计算预算和滞后 1 之间的差异。

select id, budget,
lag(budget) over (order by id) as lag1
from projects;

+----+---------+---------+
| id | budget | lag1 |
+----+---------+---------+
| 1 | 1000000 | NULL |
| 2 | 100000 | 1000000 |
| 3 | 100 | 100000 |
+----+---------+---------+

我尝试了以下两个示例,但它不起作用:

select id, budget,
ifnull(lag(budget),0) over (order by id) as lag1
from projects;

select id, budget,
ifnull((lag(budget) over (order by id) as lag1),0)
from projects;

最佳答案

lag()最多接受三个参数。第一个是返回值的表达式。这里只是列名。第二个确定它应该在后面查看多少行。默认为一个。第三个,对你来说很有趣,是一个默认值,如果没有找到前一行的话。

因此您可以直接在 lag() 调用中定义默认值:

SELECT id,
budget,
lag(budget, 1, 0) OVER (ORDER BY id) lag1
FROM projects;

关于mysql - 如何在 MySQL 中将 IFNULL 与窗口函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51351783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com