运行总计和整数值分配

时间:2018-04-30 17:17:19

标签: sql sql-server running-total

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

变量

  • @allocated int - >已经分配了分数
  • @to_allocate int - >我们现在需要分配的重点

查看"审核"

  • ts - >收集积分的日期
  • 点 - >收集的积分数

到目前为止,我只能在"审核"中的数据时获得正确的结果。是这样的:

此作品

interface IDisplay{
    void print();
    void printDetails();
}

interface IInput{
    void input();
}

class Book implements IDisplay,IInput{
    int bookID;
    String title,publisher;
    public void print(){

    }
    public void printDetails(){

    }
    public void input(){

    }
}

class Student implements IDisplay,IInput{
    int studentID;
    public void print(){

    }
    public void printDetails(){

    }
    public void input(){

    }
}

class A{
    public static void main(String[] args) {
        IDisplay id=new Student();
                id.print();
                id.printDetails();
                id.input();
    }
}

不起作用

IF OBJECT_ID('audits') IS NOT NULL
DROP VIEW audits;

GO

CREATE VIEW audits
AS
SELECT '2000-1-1' AS ts, 10 AS points UNION ALL
SELECT '2000-1-2' AS ts, 12 AS points UNION ALL
SELECT '2000-1-3' AS ts, 123 AS points UNION ALL
SELECT '2000-1-4' AS ts, 100 AS points;

GO

查询

CREATE VIEW audits
AS
SELECT '2000-1-1' AS ts, 106 AS points UNION ALL
SELECT '2000-1-2' AS ts, 12 AS points UNION ALL
SELECT '2000-1-3' AS ts, 123 AS points UNION ALL
SELECT '2000-1-4' AS ts, 100 AS points;

GO

&#34的所需输出;不起作用"数据

请注意,result列中的值不应大于相应行的值。因此,

  • 当@to_allocate为92

when @to_allocate is 92

  • 当@to_allocate为200

when @to_allocate is 200

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

1 个答案:

答案 0 :(得分:1)

这样的东西?

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

SQL Fiddle

我假设@allocated必须从多于第一行的值中删除值,尽管您的示例只有那个。