Sql 运行总值和整数值分配

Sql 运行总值和整数值分配,sql,sql-server,cumulative-sum,Sql,Sql Server,Cumulative Sum,我需要能够确定每行的剩余点数分配。让我解释一下以下问题: 变数 @已分配积分->已分配积分 @要分配int->我们现在需要分配的点 查看审核 ts->收集积分的日期 积分->收集的积分数量 到目前为止,只有当审计中的数据是这样的时候,我才能得到正确的结果: 这很有效 不起作用 质疑 不工作数据的所需输出 请注意,结果列中的值不应大于相应行的点。所以, 当@to_分配为92时 当@to_分配为200时 我可以通过使用临时表和循环来解决这个问题,但这是我不想做的事情,因为它阻止我在函数上使用它。任何

我需要能够确定每行的剩余点数分配。让我解释一下以下问题:

变数

@已分配积分->已分配积分 @要分配int->我们现在需要分配的点 查看审核

ts->收集积分的日期 积分->收集的积分数量 到目前为止,只有当审计中的数据是这样的时候,我才能得到正确的结果:

这很有效

不起作用

质疑

不工作数据的所需输出

请注意,结果列中的值不应大于相应行的点。所以,

当@to_分配为92时 当@to_分配为200时 我可以通过使用临时表和循环来解决这个问题,但这是我不想做的事情,因为它阻止我在函数上使用它。任何帮助或为我指出正确方向的人都将不胜感激。

像这样的事情

DECLARE @to_allocate int = 200
DECLARE @allocated int = 4

select *,
  points - 
  case when total < @allocated then points 
       when prev < @allocated then @allocated - prev
       else 0
  end -
  case when total > @to_allocate + @allocated 
       then total - @to_allocate - @allocated 
       else 0 
  end

from
(
  select *, lag(total, 1, 0) over (order by ts asc) as prev
  from
  (
      select *, sum(points) over (order by ts asc) as total from audits
  ) X
) X
where prev < @to_allocate + @allocated
我假设@allocated必须从不止第一行中删除值,尽管您的示例中只有这一点。

类似的内容

DECLARE @to_allocate int = 200
DECLARE @allocated int = 4

select *,
  points - 
  case when total < @allocated then points 
       when prev < @allocated then @allocated - prev
       else 0
  end -
  case when total > @to_allocate + @allocated 
       then total - @to_allocate - @allocated 
       else 0 
  end

from
(
  select *, lag(total, 1, 0) over (order by ts asc) as prev
  from
  (
      select *, sum(points) over (order by ts asc) as total from audits
  ) X
) X
where prev < @to_allocate + @allocated

我假设@allocated必须从不止第一行中删除值,尽管您的示例中只有这些值。

是的,绝对是。这听起来太简单了:PYes,绝对是。这听起来太简单了:p
DECLARE @to_allocate int = 92;
DECLARE @allocated int = 4;

WITH result
AS
(
    SELECT 
        ts,
        points,
        SUM(points) OVER(ORDER BY ts) AS total
    FROM audits
),
points
AS
(
    SELECT 
        ts,
        points,
        total,
        CASE 
            WHEN @to_allocate > total - @allocated THEN total - @allocated
            ELSE @to_allocate - SUM(total - @allocated) 
                                OVER(ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
        END as result
    FROM result
)
SELECT * FROM points
WHERE result > 0;
DECLARE @to_allocate int = 200
DECLARE @allocated int = 4

select *,
  points - 
  case when total < @allocated then points 
       when prev < @allocated then @allocated - prev
       else 0
  end -
  case when total > @to_allocate + @allocated 
       then total - @to_allocate - @allocated 
       else 0 
  end

from
(
  select *, lag(total, 1, 0) over (order by ts asc) as prev
  from
  (
      select *, sum(points) over (order by ts asc) as total from audits
  ) X
) X
where prev < @to_allocate + @allocated