sql serverは払い戻し総額をできるだけ少ない複数の注文に分割します。


一、問題
もとは3つのチャージ注文がありましたが、今は450元を返金したいですが、どうやって配分すれば今回の払い戻しに関わるチャージオーダーの数が一番少ないですか?具体的なデータは下図を参照してください。

二、解決策
Step 1:キャンセル可能金額を降順に並べて、キャンセル可能金額が大きい注文を優先的に使う
Step 2:CTE共通表現を使用して、forまたはwhileループまたはラベルのような機能を実現する
三、脚本

create table #t
(
     int,
     int,
     int
)
insert into #t(  ,   ,   )
values (200, 100, 100), (500, 200, 300), (300, 100, 200)

/*
  :zhang502219048
    :https://www.cnblogs.com/zhang502219048/p/14127208.html
*/

declare @i   int = 450;
with cte1 as
(
  select *, row_number() over(order by    desc) rn, 0      , 0   
  from #t
),
cte2 as
(
  select rn,   ,   ,   , 
          = case when @i   >    then    else @i   end, 
       = @i   - case when @i   >    then    else @i   end --    =    -      
  from cte1
  where rn = 1
  union all
  select t2.rn, t2.  , t2.  , t2.  ,
          = case when t1.   > t2.   then t2.   else t1.   end, 
       = t1.   - case when t1.   > t2.   then t2.   else t1.   end
  from cte1 t2
  inner join cte2 t1 on t1.rn = t2.rn - 1 -- t2 t1      
  --where t2.rn > 1 and t1.   > 0
)
select * from cte2

drop table #t
四、スクリプトの実行結果

締め括りをつける
このページでsql serverについては、払戻し総額をできるだけ少ない数の注文に分割した文章を紹介します。もっと関連のあるsql serverの払戻総額を注文書の内容に分割してください。以前の文章を検索してください。また、下記の関連記事をご覧ください。これからもよろしくお願いします。