SQL如何计算这种情况?

时间:2020-08-22 06:11:48

标签: sql sql-server sum window-functions gaps-and-islands

我需要帮助查询情况以计算情况,我不知道如何查询情况。

请任何帮助我继续进行此项目的人,您可以为我提供指导和示例

这是我的数据样本:

Date       Usage  Plan
------------------------
2020-04-30 NULL   94928
2020-05-01 NULL   NULL
2020-05-02 NULL   NULL
2020-05-03 12269  NULL
2020-05-04 3253   NULL
2020-05-05 NULL   NULL
2020-05-06 NULL   NULL
2020-05-07 NULL   NULL
2020-05-08 500    1000
2020-05-09 NULL   NULL
2020-05-10 NULL   NULL
2020-05-11 NULL   NULL

所需的输出如下:

Date       Usage  Plan
-----------------------
2020-04-30 NULL   94928
2020-05-01 NULL   94928
2020-05-02 NULL   94928
2020-05-03 12269  82659
2020-05-04 3253   79406
2020-05-05 NULL   79406
2020-05-06 NULL   79406
2020-05-07 NULL   79406
2020-05-08 500    1000
2020-05-09 NULL   500
2020-05-10 NULL   500
2020-05-11 NULL   500

为示例数据创建表脚本:

CREATE TABLE [dbo].[Table_1]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [Date] [date] NULL,
    [ITEM_NUMBER] [varchar](max) NULL,
    [Plan_Matusage] [int] NULL,
    [St_plan] [int] NULL,
    [St_revise] [int] NULL,
    [St_actual] [int] NULL,
)

2 个答案:

答案 0 :(得分:1)

您可以使用窗口功能。这个想法是用窗口总和来构建相邻记录的组,该窗口总和对于每个非空[3, 2, 4]

plan

答案 1 :(得分:0)

这有效

with plan_group_cte as (
    select  t.*, sum(iif([Plan] is not null, 1, 0)) over(order by [Date]) plan_group
    from dbo.Table_1 t)
select [Date], [Usage], 
       coalesce([Plan],  (max([Plan]) over (partition by plan_group)-
       sum(cast([Usage] as int)) over (partition by plan_group order by [Date]))) [Plan]
from plan_group_cte
order by 1;