C# 在SQL server中给定一个由n个数字组成的排序行,如何找到行的总和在什么时候达到k值?
假设我得到了下面一行数字,最大数量值是10C# 在SQL server中给定一个由n个数字组成的排序行,如何找到行的总和在什么时候达到k值?,c#,sql,sql-server,algorithm,math,C#,Sql,Sql Server,Algorithm,Math,假设我得到了下面一行数字,最大数量值是10 Quantity BatchValue 2 0 4 0 4 0 6 1 8 2 2+4+4之和给出的值小于或等于最大数量10,因此这些行的批处理值变为0。挂起的行是6和8。它们不能总结为
Quantity BatchValue
2 0
4 0
4 0
6 1
8 2
2+4+4之和给出的值小于或等于最大数量10,因此这些行的批处理值变为0。挂起的行是6和8。它们不能总结为<最大数量。所以他们会分开。我们可以得到一个sql查询或一个算法来实现这一点吗?这里有一个很好的运行求和例程,您可以使用它
create table #temp (rowid int identity, quantity int)
insert #temp
select quantity from yourtable order by your order
declare @holding table (quantity int, runningsum int)
declare @quantity int
declare @running int=0
declare @iterator int = 1
while @iterator<=(select max(rowid) from #temp)
begin
select @quantity=quantity from #temp where rowid=@iterator
set @running=@quantity+@running
insert @holding
select @quantity, @running
set @iterator=@iterator+1
end
create table#temp(rowid int identity,quantity int)
插入#温度
按订单从表格订单中选择数量
声明@holding table(数量整数,运行总数整数)
声明@quantity int
声明@running int=0
声明@iterator int=1
而@iterator编辑了上面Daniel Marcus的代码,以给出查询中请求的实际响应
CREATE TABLE #temp(rowid int identity(1,1), quantity int)
INSERT INTO #temp
SELECT 2
UNION ALL SELECT 4
UNION ALL SELECT 4
UNION ALL SELECT 6
UNION ALL SELECT 8
declare @batchValue int = 0 ,@maxquantity int = 10
declare @holding table (quantity int, batchvalue int)
declare @quantity int
declare @running int=0
declare @iterator int = 1
while @iterator<=(select max(rowid) from #temp)
begin
select @quantity=quantity from #temp where rowid=@iterator
set @running=@quantity+@running
-- Newly added condition
if (@running > @maxquantity) BEGIN
SET @batchValue = @batchValue + 1 -- increment the batch value
insert @holding select @quantity, @batchValue
SET @running = @quantity -- reset the running value
END
ELSE
insert @holding select @quantity, @batchValue
set @iterator=@iterator+1
end
SELECT * FROM @holding
DROP TABLE #temp
CREATE TABLE#temp(rowid int identity(1,1),quantity int)
插入#temp
选择2
联合所有选择4
联合所有选择4
联合所有选择6
联合所有选择8
声明@batchValue int=0,@maxquantity int=10
声明@holding table(数量int,批处理值int)
声明@quantity int
声明@running int=0
声明@iterator int=1
当@iterator@maxquantity)开始时
设置@batchValue=@batchValue+1——增加批处理值
插入@holding select@数量,@batchValue
设置@running=@quantity——重置运行值
终止
其他的
插入@holding select@数量,@batchValue
设置@iterator=@iterator+1
终止
从@holding中选择*
升降台#温度
希望这段代码对您有用。我在SQL azure中对此进行了测试,并提供了您提到的结果。--如果您使用的是SQL server 2012或更高版本,下面的查询将对您有所帮助
创建表#RUN_TOT(ID INT)
插入#运行总计值(2)、(4)、(4)、(6)、(8)
);以CTE为例
(
选择ID,
(按ID排序)RNUM上的行号(),
案例
当SUM(ID)超过(无界前一行和当前行之间按ID排序的行)时,您所需的输出是什么样子的?您尝试了什么查询?搜索此站点以查找运行总计。它已被询问和回答多次。