t-sql loop through all rows and sum amount from column until value is reached

后端 未结 1 1954
广开言路
广开言路 2021-01-24 17:37

I have a table containing the below test data:

I now would like to fill a restaurant with 12 seating spaces.

This should result in:

相关标签:
1条回答
  • 2021-01-24 17:42

    Because you want to skip rows, you need a recursive CTE. But it is tricky -- because you may not have a group following your rules that adds up to exactly 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 is a db<>fiddle.

    Note that if you change "I" to a larger value, then it is not included and the number of occupied seats is 11, not 12.

    0 讨论(0)
提交回复
热议问题