sql >> データベース >  >> RDS >> Sqlserver

SQL Server:合計が値と一致する行を選択します

    これを解決するには、MSSQLで再帰クエリを使用できます。

    SQLFiddleデモ

    最初の再帰クエリは、累積合計が150未満のアイテムのツリーを構築します。2番目の再帰クエリは、累積合計が150のリーフを取得し、そのようなすべてのパスをルートに出力します。 ItemsCountで並べ替えられた最終結果でも そのため、最初に優先グループ(最小アイテム数)を取得します。

    WITH CTE as
    ( SELECT id,num,
             id as Grp,
             0 as parent,
             num as CSum,
             1 as cnt,
             CAST(id as Varchar(MAX)) as path
         from T where num<=150
      UNION all
      SELECT t.id,t.num,
             CTE.Grp as Grp, 
             CTE.id as parent,
             T.num+CTE.CSum as CSum,
             CTE.cnt+1 as cnt,
             CTE.path+','+CAST(t.id as Varchar(MAX)) as path
        from T 
      JOIN CTE on T.num+CTE.CSum<=150 
                 and CTE.id<T.id 
    ),
    BACK_CTE as
    (select CTE.id,CTE.num,CTE.grp, 
             CTE.path ,CTE.cnt as cnt,
             CTE.parent,CSum 
        from CTE where CTE.CSum=150
      union all
      select CTE.id,CTE.num,CTE.grp,
             BACK_CTE.path,BACK_CTE.cnt, 
             CTE.parent,CTE.CSum 
       from CTE
       JOIN BACK_CTE on CTE.id=BACK_CTE.parent 
                  and CTE.Grp=BACK_CTE.Grp
                  and BACK_CTE.CSum-BACK_CTE.num=CTE.CSum
    ) 
    select id,NUM,path, cnt as ItemsCount   from BACK_CTE order by cnt,path,Id
    


    1. テーブル内のすべての日付を更新する方法

    2. サーバー上のDB接続を管理する方法は?

    3. ホストは、クライアントサーバーアプリケーションのためにこのMySQLサーバーに接続することを許可されていません

    4. pandas.DataFrame.to_sqlからの挿入を高速化する方法