我有一个包含以下测试数据的表:
我现在想在一家餐厅里装满12座位空间。
这应该导致:
基本上,我需要从上到下循环遍历所有行并添加 AmountPersons 直到填满餐厅。
在这个例子中:
(前几行:AmountPersons)3+1+2+4 = 10
UserId 52 无法添加,因为他们预留了 3 人,这将导致 13 个位置被占用,而只剩下 12 个可用位置。
在下一行中,它注意到 1 号的预订。这可以添加到我们已经找到的前 10 号中。
新总计现在为 11。
无法添加 UserId 79 和 82,因为我们会再次超出容量。
UserId 95 保留为 1,这个可以添加,现在所有位置都填满了。
这是我从我使用的光标得到的结果,但我现在卡住了。请帮忙。
当下一个值高于 12 时,游标中的 while 循环基本上停止。但这是不正确的。
因为要跳过行,所以需要递归 CTE。但这很棘手——因为你可能没有一个遵循你的规则的小组的总人数加起来正好是 12。
So:
with tn as (
select t.*, row_number() over (order by userid) as seqnum
from t
),
cte as (
select userId, name, amountPersons as total, 1 as is_included, seqnum
from tn
where seqnum = 1
union all
select tn.userId, tn.name,
(case when tn.amountPersons + cte.total <= 12
then tn.amountPersons + cte.total
else cte.total
end),
(case when tn.amountPersons + cte.total <= 12
then 1
else 0
end) as is_included,
tn.seqnum
from cte join
tn
on tn.seqnum = cte.seqnum + 1
where cte.total < 12
)
select cte.*
from cte
where is_included = 1;
Here是一个数据库小提琴。
请注意,如果将“I”更改为更大的值,则不包括在内,占用的座位数为 11,而不是 12。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)