【问题标题】:Add a 0 in the next row of a column after the last data point在最后一个数据点之后的列的下一行中添加 0
【发布时间】:2020-11-24 10:31:48
【问题描述】:

我写了一个查询,输出如下所示:

Date                           Amount
01-01-2020                          
01-02-2020                      10000
01-03-2020                      20000
01-04-2020                      30000
01-05-2020                      40000
01-06-2020                           
01-07-2020                           
01-08-2020                           

在上表中,我们可以看到 01-01-2020、01-06-2020、01-07-2020、01-08-2020 的金额为空。现在,我想为仅 1 行的金额列添加 0,即日期 - 01-06-2020,它在最后一个数据点 - 40000 之后。我不知道该怎么做。有没有直接的查询来实现这一点?谢谢。

【问题讨论】:

  • 我们是否保证所有填充的值都是连续的?如果不是,是否每个组都被单独处理,还是真的只是触发零的最后一个值?
  • 值 0 与上面的数字没有任何关系。我必须在另一个应用程序中借助此输出创建一个图表,并且我必须在最后一个数据点之后有一个 0。 (在我们的例子中,40000 后为 0)
  • 如果 01-07-2020 也有数据怎么办?如果有的话,您希望更改哪些行?

标签: sql sql-server datetime sql-update


【解决方案1】:

您可以使用lag()case 表达式:

select date,
    case when amount is null and lag(amount) over(order by date) is not null 
        then 0
        else amount
    end as amount
from mytable

如果您想要update 声明:

with cte as (
    select amount,
        case when amount is null and lag(amount) over(order by date) is not null 
            then 0
        end as new_amount
    from mytable
)
update cte set amount = new_amount where new_amount = 0

【讨论】:

  • 当我在更新语句中使用上述代码时,我得到“窗口函数只能出现在 SELECT 或 ORDER BY 子句中”。
  • @BrawlX:我用update 声明更新了我的答案。
  • @BrawlX,请将其标记为答案。所以,对以后的其他人有帮助
猜你喜欢
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多